【问题标题】:How do I convert the following xml into java objects using JAXB如何使用 JAXB 将以下 xml 转换为 java 对象
【发布时间】:2015-08-06 22:23:25
【问题描述】:

将此 XML 转换为 Java 对象的最佳方法是什么?

<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>

最好使用带有 HashMap 的自定义 XMLAdapter 来转换 &lt;customer&gt; 的多个 xml 行吗?
我不确定 XMLAdapter 是否适合这种情况。任何想法将不胜感激。

【问题讨论】:

标签: java xml jaxb jaxb2


【解决方案1】:

由于嵌套不是很深,你可以只拥有 Entity、Customer 类,然后在实体类中使用这些注解进行映射:

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

参考资料: XmlElementWrapper

【讨论】:

    【解决方案2】:

    在我看来,最好的方法是编写一个 xsd 文件来验证您的 xml。您可以使用它来使用与 Java 捆绑在一起的 xjc 生成您的 Java 类。这应该能让你到达那里。

    <?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>
    

    在您放置 xsd 文件的文件夹中打开命令提示符,然后生成您只需键入的 java 代码:

    $ xjc nameOfSchemaFile.xsd
    

    假设您的 java 'bin' 文件夹在您的路径中。生成的类将在与您的 targetNamespace 同名的文件夹中创建。

    使用这些,您可以按照 Naimish 的示例 JAXB Hello World Example 中的说明进行操作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-21
      相关资源
      最近更新 更多