以有效的方式将 XML 解析为 JAVA POJO

2022-09-04 08:32:28

如何以有效的方式解析和创建以下xml的java pojo?请建议任何有效的解析器。

XML 格式为

<?xml version="1.0" encoding="utf-8"?>
<CCMainRootTag ID="12">
  <Header TableName="TableName"    TableVersion="12" TableID="12" CreatedDate="2013-02-09T15:35:33" CreatedByUserName="ABC" CreatedBySystem="ABC" />
  <ClassPrimary ID="12" Code="Y" DescriptionDK="DK language " DescriptionUK="" DefDK="" DefUK="" IFDGUID="">
    <ObjectClass ID="12" Code="YA" DescriptionDK="DK Language" DescriptionUK="" DefDK=""     DefUK="" IFDGUID="">
      <Synonym>
        <Concept Description="Description" Language="DK" />
        <Concept Description="" Language="UK" />
        <Concept Description="Description" Language="DK" />
        <Concept Description="" Language="UK" />
        <Concept Description="Description" Language="DK" />
        <Concept Description="" Language="UK" />
        <Concept Description="Description" Language="DK" />
        <Concept Description="" Language="UK" />
      </Synonym>
    </ObjectClass>
    <ObjectClass ID="12" Code="YB" DescriptionDK="DK Language" DescriptionUK="" DefDK="" DefUK="" IFDGUID=""> </ObjectClass>
    <ObjectClass ID="12" Code="YC" DescriptionDK="DK Language" DescriptionUK="" DefDK="" DefUK="" IFDGUID=""> </ObjectClass>
    <ObjectClass ID="12" Code="YD" DescriptionDK="DK language" DescriptionUK="" DefDK="" DefUK="" IFDGUID=""> </ObjectClass>
  </ClassPrimary>
</CCMainRootTag>

我已经使用了这个链接,但它的性能很慢,并且有问题没有有效的pojo。

我想解析器,它以有效的方式为我提供直接的java pojo。


答案 1

您可以使用 JAXB 将 XML 转换为 Java POJO。但在最终确定解决方案之前,请检查此站点以进行性能比较。


答案 2

对于那些寻找JAXB代码将xml转换为java对象的人:

//Convert xml to String first
Element partyLoaderRequest; // your xml data
String xmlString = new XMLOutputter().outputString(partyLoaderRequest);   
InputStream is = new ByteArrayInputStream(xmlString.getBytes());
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = docBuilder.parse(is);
org.w3c.dom.Element varElement = document.getDocumentElement();
JAXBContext context = JAXBContext.newInstance(Person.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
JAXBElement<Person> loader = unmarshaller.unmarshal(varElement, Person.class);
Person inputFromXml = loader.getValue();

而 Person 具有适当的 XML 注释:

@XmlRootElement(name="Person")
public class CimbWlAdminUserAmendInput {
    @XmlElement(name="companyName",required=true,nillable=false) 
    private String companyName;
    ...
    //setters getters
    @XmlTransient
    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }
}

推荐