Java:如何将ArrayList转换为XML?
您好,感谢您阅读此问题: 我将首先解释用例和我尝试过的方法:Java:如何将ArrayList转换为XML?,java,xml,arraylist,Java,Xml,Arraylist,您好,感谢您阅读此问题: 我将首先解释用例和我尝试过的方法: /* * 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 j
/*
* 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);
}
}
}
我有一个保存课程数据的ArrayList,它在FrontServlet中创建,并存储在会话中
我想将ArrayList转换为XML,将其显示为HTML,并使用XSL进行转换
我怀疑的是:我们如何将ArrayList转换为XML
我研究了如何注释类以转换它们:
我使用了静态XML对其进行转换并显示:
我读过一篇关于扩展ArrayList以使其能够转换的文章:
我首先尝试了:
/*
* 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);
}
}
}
谢谢您的帮助。您可以使用xstream将对象转换为xml。 Maven依赖项:
<dependency>
<groupId>xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.2.2</version>
</dependency>
主类
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;
}
}
公共类主{
公共静态void main(字符串[]args){
XMLTransformer=XMLTransformer.getInstance();
员工e1=新员工(“gati”、“id”);
员工e2=新员工(“gati”、“id”);
员工e3=新员工(“gati”、“id”);
List employeeList=新建ArrayList();
新增(e1);
新增(e2);
新增(e3);
String str=transformer.toXMLString(员工列表);
系统输出打印项次(str);
}
}
公营雇员{
私有字符串名称;
私人字符串电子邮件;
公共雇员(字符串名称、字符串电子邮件){
this.name=名称;
this.email=电子邮件;
}
公共字符串getName(){
返回名称;
}
公共void集合名(字符串名){
this.name=名称;
}
公共字符串getEmail(){
回复邮件;
}
公用电子邮件(字符串电子邮件){
this.email=电子邮件;
}
}