Java:我们如何将ArrayList转换为XML?

时间:2018-02-20 10:17:41

标签: java xml arraylist

您好,感谢您阅读此问题:

我将首先解释用例以及我尝试过的方法:

我有一个ArrayList,它保存Courses'data,它正在FrontServlet中创建,并存储在会话中。

我想将ArrayList转换为XML,将其显示为使用XSL转换它的HTML。

我怀疑的是:我们怎样才能将ArrayList转换为XML?

我研究过如何注释类来转换它们:https://www.mkyong.com/java/jaxb-hello-world-example/

我使用静态XML对其进行转换并显示它:Java: Implementing Transform View pattern, to convert XML to HTML with an XSL file

我读过一篇关于扩展ArrayList<>的文章。能够改变它:Why my ArrayList is not marshalled with JAXB?

我首先尝试过:

/*
 * 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;
    }

}

但是我不需要Curso类本身,我需要转换存储它们的ArrayList。

此外,我目前正在会话中存储正在创建的课程。我们怎样才能在servlet中获取会话的信息?我的意思是,我们可以从当前创建的servlet和JSP页面访问它们,但是我们如何访问servlet呢?

我问上一个问题,因为在我发现的将Java转换为XML的所有示例中,它们都显示了新实例,而不是如何转换以前存储的实例。

我试过的代码:

/*
 * 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);
        }
    }

}

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您可以使用xstream将对象转换为xml。 Maven依赖:

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

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);
    }

}

主要课程

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;
    }
}