简体   繁体   English

Java:如何将ArrayList转换为XML?

[英]Java: How could we convert an ArrayList to XML?

Hello and thank you for reading this question: 您好,感谢您阅读以下问题:

I will explain the use case first and the approach I have tried: 我将首先解释用例和尝试过的方法:

I have an ArrayList which holds Courses'data and it is being created in the FrontServlet and it is being stored in the session. 我有一个保存课程数据的ArrayList,它在FrontServlet中创建,并存储在会话中。

I would like to convert the ArrayList to XML to show it as HTML transforming it with XSL. 我想将ArrayList转换为XML,以HTML形式显示,并使用XSL对其进行转换。

Mi doubt is: how could we convert an ArrayList to XML? 小米怀疑是:我们如何将ArrayList转换为XML?

I have studied how to annotate classes to transform them: https://www.mkyong.com/java/jaxb-hello-world-example/ 我研究了如何注释类以对其进行转换: https : //www.mkyong.com/java/jaxb-hello-world-example/

I have used an static XML to convert it and show it: Java: Implementing Transform View pattern, to convert XML to HTML with an XSL file 我使用了静态XML进行转换并显示它: Java:实现Transform View模式,以XSL文件将XML转换为HTML

I have read a good post about extending ArrayList<> to be able to transform it: Why my ArrayList is not marshalled with JAXB? 我已经阅读了一篇有关扩展ArrayList <>使其能够转换的好文章: 为什么我的ArrayList没有与JAXB一起编组?

I first tried with: 我首先尝试了:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author YonePC
 */
@XmlRootElement
public class Curso {

    @XmlElement
    public void setTitulo(String titulo) {
        this.titulo = titulo;
    }

    @XmlElement
    public void setAutor(String autor) {
        this.autor = autor;
    }

    @XmlElement
    public void setAsignatura(String asignatura) {
        this.asignatura = asignatura;
    }

    @XmlElement
    public void setDuracion(String duracion) {
        this.duracion = duracion;
    }

    @XmlElement
    public void setVideo(String video) {
        this.video = video;
    }
    String titulo, autor, asignatura, duracion, video;

    public Curso(String titulo, String autor, String asignatura, String duracion, String video) {
        this.titulo = titulo;
        this.autor = autor;
        this.asignatura = asignatura;
        this.duracion = duracion;
        this.video = video;
    }

    public String getTitulo() {
        return titulo;
    }

    public String getAutor() {
        return autor;
    }

    public String getAsignatura() {
        return asignatura;
    }

    public String getDuracion() {
        return duracion;
    }

    public String getVideo() {
        return video;
    }

}

But I do not need the Curso class itself, I need to convert the ArrayList which stores them. 但是我不需要Curso类本身,我需要转换存储它们的ArrayList。

In addition, I currently stores the courses being created in the session. 另外,我目前存储在会话中创建的课程。 How could we get the session's info in a servlet? 我们如何在servlet中获取会话的信息? I mean, we can access them from the servlet where it has being currently created, and from JSP pages, but how do we do access into servlets? 我的意思是,我们可以从当前创建它的servlet和JSP页面访问它们,但是我们如何访问servlet?

I ask the previous question because in all the examples I found about converting Java to XML, they showed new instances and not how to convert previous stored ones. 我问上一个问题,因为在我发现的所有有关将Java转换为XML的示例中,它们都显示了新实例,而不是如何转换先前存储的实例。

The code I have tried: 我尝试过的代码:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package frontController;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.Curso;

/**
 *
 * @author YonePC
 */
@WebServlet(name = "CourseInfoCommand", urlPatterns = {"/CourseInfoCommand"})
public class CourseInfoCommand extends FrontCommand {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    @Override
    public void process(HttpServletRequest request) {
        try {

            File file = new File("C:\\Users\\YonePC\\Videos\\ASAPLICACIONCURSOSPRACTICA1\\src\\java\\frontController\\Cursos.xml");
            ArrayList courses = (ArrayList) session.getAttribute("cursos");

            JAXBContext jaxbContext = JAXBContext.newInstance(ArrayListCourses.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

            jaxbMarshaller.marshal(courses, file);

            TransformerFactory factory = TransformerFactory.newInstance();
            StreamSource xsl = new StreamSource(new File(""));
            Transformer newTransformer = factory.newTransformer(xsl);

            StreamSource xml = new StreamSource(new File(""));
            PrintWriter writer = response.getWriter();
            Result result = new StreamResult(writer);
            newTransformer.transform(xml, result);
            writer.println(writer.toString());

            forward("/CourseInfo.jsp");
        } catch (ServletException ex) {
            Logger.getLogger(CourseInfoCommand.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(CourseInfoCommand.class.getName()).log(Level.SEVERE, null, ex);
        } catch (TransformerConfigurationException ex) {
            Logger.getLogger(CourseInfoCommand.class.getName()).log(Level.SEVERE, null, ex);
        } catch (TransformerException ex) {
            Logger.getLogger(CourseInfoCommand.class.getName()).log(Level.SEVERE, null, ex);
        } catch (JAXBException ex) {
            Logger.getLogger(CourseInfoCommand.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

Thank you for your help. 谢谢您的帮助。

You can use xstream to transform the object to xml. 您可以使用xstream将对象转换为xml。 Maven dependency: Maven的依赖:

 <dependency>
        <groupId>xstream</groupId>
        <artifactId>xstream</artifactId>
        <version>1.2.2</version>
    </dependency>

XMLTransformer: XMLTransformer:

public class XMLTransformer {
    private XStream xstream = null;

    private XMLTransformer() {
        xstream = new XStream();
    }

    public static XMLTransformer getInstance() {
        return new XMLTransformer();
    }

    public String toXMLString(Object object) {
        return xstream.toXML(object);
    }

    public Object toObject(String xml) {
        return (Object) xstream.fromXML(xml);
    }

}

Main class 主班

public class Main {

    public static void main(String[] args) {
        XMLTransformer transformer=XMLTransformer.getInstance();
        Employee e1=new Employee("gati","id");
        Employee e2=new Employee("gati","id");
        Employee e3=new Employee("gati","id");
        List<Employee> employeeList =new ArrayList<>();
        employeeList.add(e1);
        employeeList.add(e2);
        employeeList.add(e3);
        String str=transformer.toXMLString(employeeList);
       System.out.println(str);
    }

}


public class Employee {
    private String name;
    private String email;

    public Employee(String name, String email) {
        this.name = name;
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM