有如下xml:
- <?xml version="1.0" encoding="UTF-8"?>
- <pdf_report_data>
- <info>AA1334</info>
- <reportData>
- <name>demo</name>
- <address>demo address</address>
- <telno>12345678</telno>
- </reportData>
- <reportData>
- <name>demo</name>
- <address>demo address</address>
- <telno>12345678</telno>
- </reportData>
- <reportData>
- <name>demo</name>
- <address>demo address</address>
- <telno>12345678</telno>
- </reportData>
- </pdf_report_data>
如何定义 JAXB 实体类,以便装配的时候输出对应的 xml ?
- import jakarta.xml.bind.*;
- import java.util.ArrayList;
- import java.util.List;
- import java.io.StringWriter;
- @XmlAccessorType(XmlAccessType.FIELD)
- @XmlElement(name = "pdf_report_data")
- public class PdfReportData {
-
- @XmlElement(name = "info")
- private String info;
-
- @XmlElement(name = "reportData")
- private List<ReportData> reportDataList;
-
-
-
- public static void main(String[] args) throws JAXBException {
- PdfReportData pdfReportData = new PdfReportData();
- pdfReportData.setInfo("AA1334");
- List<ReportData> reportDataList = new ArrayList<>();
- ReportData reportData1 = new ReportData();
- reportData1.setName("demo");
- reportData1.setAddress("demo address");
- reportData1.setTelno("12345678");
- reportDataList.add(reportData1);
-
- pdfReportData.setReportDataList(reportDataList);
- JAXBContext jaxbContext = JAXBContext.newInstance(PdfReportData.class);
- Marshaller marshaller = jaxbContext.createMarshaller();
- marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
- StringWriter stringWriter = new StringWriter();
- marshaller.marshal(pdfReportData, stringWriter);
- String xmlString = stringWriter.toString();
- System.out.println(xmlString);
- }
-
- @XmlAccessorType(XmlAccessType.FIELD)
- public static class ReportData {
- @XmlElement(name = "name")
- private String name;
- @XmlElement(name = "address")
- private String address;
- @XmlElement(name = "telno")
- private String telno;
-
- }
- }