How do I convert the following xml into java objects using JAXB

天涯浪子 提交于 2019-12-25 12:27:07

问题


What is the best way to convert this XML into Java objects?

<entity>         
    <customers id=2 other="data">
        <customer name="john">testData1</customer>
        <customer name="jenny">testData2</customer>
        <customer name="joe">testData3</customer>
        <customer name="joanna">testData4</customer>
    </customers>
</entity>

Is it best to use a custom XMLAdapter with a HashMap to convert multiple xml rows of <customer>?
I'm not sure if the XMLAdapter is the proper use case for this scenario. Any ideas would be appreciated.


回答1:


Since the nesting isn't very deep, you could just have Entity, Customer classes and then use these annotations for the mapping in the entity class:

@XmlElementWrapper(name="customers")
@XmlElement(name="customer")
public void setCustomers(List<Customer> customers) {
    this.customers= customers;
}

References: XmlElementWrapper




回答2:


Best approach, in my opinion, would be to write an xsd file to validate against your xml. You can use that to generate your java classes using xjc which comes bundled with Java. This should get you there.

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
        xmlns:NameOfNamespace="http://enter.your.namespace.here"
        targetNamespace="http://enter.your.namespace.here"
        attributeFormDefault="unqualified"
        elementFormDefault="qualified">

    <complexType name="customer">
        <simpleContent>
            <extension base="string">
                <attribute name="name"/>
            </extension>
        </simpleContent>
    </complexType>

    <complexType name="customers">
        <sequence>
            <element name="customer" type="NameOfNamespace:customer"/>
        </sequence>
        <attribute name="id" type="positiveInteger"/>
        <attribute name="other"/>
    </complexType>

    <complexType name="entity" >
        <sequence>
            <element name="customers" type="NameOfNamespace:customers" minOccurs="1" maxOccurs="1"/>
        </sequence>
    </complexType>

    <element name="entity" type="NameOfNamespace:entity"/>
</schema>

Open a command prompt to the folder where you put your xsd file, and then generate java code you'll just need to type:

$ xjc nameOfSchemaFile.xsd

assuming your java 'bin' folder is in your path. The classes generated will be created in folder with the same name as your targetNamespace.

Using these you can follow the instructions in Naimish's example JAXB Hello World Example



来源:https://stackoverflow.com/questions/31842080/how-do-i-convert-the-following-xml-into-java-objects-using-jaxb

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!