首页  编辑  

Java/JAXB装配xml时 List 在根目录下的处理方法

Tags: /Java/   Date Created:
有如下xml:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <pdf_report_data>
  3.   <info>AA1334</info>
  4.   <reportData>
  5.    <name>demo</name>
  6.    <address>demo address</address>
  7.    <telno>12345678</telno>
  8.   </reportData>
  9.   <reportData>
  10.    <name>demo</name>
  11.    <address>demo address</address>
  12.    <telno>12345678</telno>
  13.   </reportData>
  14.   <reportData>
  15.    <name>demo</name>
  16.    <address>demo address</address>
  17.    <telno>12345678</telno>
  18.   </reportData>
  19. </pdf_report_data>
如何定义 JAXB 实体类,以便装配的时候输出对应的 xml ?
  1. import jakarta.xml.bind.*;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import java.io.StringWriter;
  5. @XmlAccessorType(XmlAccessType.FIELD)
  6. @XmlElement(name = "pdf_report_data")
  7. public class PdfReportData {
  8.     
  9.     @XmlElement(name = "info")
  10.     private String info;
  11.     
  12.     @XmlElement(name = "reportData")
  13.     private List<ReportData> reportDataList;
  14.     
  15.     // Constructors, getters, and setters
  16.     
  17.     public static void main(String[] args) throws JAXBException {
  18.         PdfReportData pdfReportData = new PdfReportData();
  19.         pdfReportData.setInfo("AA1334");
  20.         List<ReportData> reportDataList = new ArrayList<>();
  21.         ReportData reportData1 = new ReportData();
  22.         reportData1.setName("demo");
  23.         reportData1.setAddress("demo address");
  24.         reportData1.setTelno("12345678");
  25.         reportDataList.add(reportData1);
  26.         // 添加更多的 ReportData 对象...
  27.         pdfReportData.setReportDataList(reportDataList);
  28.         JAXBContext jaxbContext = JAXBContext.newInstance(PdfReportData.class);
  29.         Marshaller marshaller = jaxbContext.createMarshaller();
  30.         marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
  31.         StringWriter stringWriter = new StringWriter();
  32.         marshaller.marshal(pdfReportData, stringWriter);
  33.         String xmlString = stringWriter.toString();
  34.         System.out.println(xmlString);
  35.     }
  36.     
  37.     @XmlAccessorType(XmlAccessType.FIELD)
  38.     public static class ReportData {
  39.         @XmlElement(name = "name")
  40.         private String name;
  41.         @XmlElement(name = "address")
  42.         private String address;
  43.         @XmlElement(name = "telno")
  44.         private String telno;
  45.         // Constructors, getters, and setters
  46.     }
  47. }