JAXB将XML解组为HashMap

时间:2016-04-13 11:18:18

标签: java xml jaxb

我有一个复杂的XML结构,如下所示需要解组:

<abc>
      <pqr>
        <attribute>name</attribute>
        <entry>
          <priorityKey>
            <class>123</class>
            <reason>abc</reason>
          </prioritykey>
          <priority> 1 </priority>
        </entry>

        <entry>
          <prioritykey>
            <class>456</class>
            <reason>abc1</reason>
          </prioritykey>
          <priority>2</priority>
        </entry>
      </pqr>

      <pqr>
       '''
       '''
      </pqr>
    </abc>

abc 是根节点。它可以有多个 pqr 元素。每个pqr元素都有一个属性节点和多个条目节点。所以我相信它将是HashMap类型(条目,属性)。

每个条目依次具有 prioritykey 优先级,我认为它们的类型为HashMap(优先级,优先级)。

需要解组此xml但不知道如何配置XMLAdapter

1 个答案:

答案 0 :(得分:0)

在这里,首先创建合同。我在学习过程中创建了一个......

<xs:element name="abc" type="abcType" />

<xs:complexType name="abcType">
    <xs:sequence>
        <xs:element name="pqr" type="pqrType" minOccurs="1"
            maxOccurs="unbounded" />
    </xs:sequence>
</xs:complexType>
<xs:complexType name="pqrType">
    <xs:sequence>
        <xs:element name="attribute" type="xs:string" minOccurs="1"
            maxOccurs="1" />
        <xs:element name="entry" type="entryType" minOccurs="1"
            maxOccurs="unbounded" />
    </xs:sequence>
</xs:complexType>

<xs:complexType name="entryType" >
    <xs:sequence>
        <xs:element name="priorityKey" type="priorityKeyType"
            minOccurs="1" maxOccurs="1" />
        <xs:element name="priority" type="xs:int" minOccurs="1"
            maxOccurs="1" />
    </xs:sequence>
</xs:complexType>
<xs:complexType name="priorityKeyType">
    <xs:sequence>
        <xs:element name="class" type="xs:int" minOccurs="1"
            maxOccurs="1" />
        <xs:element name="reason" type="xs:string" minOccurs="1"
            maxOccurs="1" />
    </xs:sequence>
</xs:complexType>

将其复制并保存在fileName.xsd文件中。 现在,生成JAXB类或工件。如果您使用的是IDE,那么这很简单。单击fileName.xsd文件,您应该获得一些生成JAXB工件的选项。否则,您始终可以使用JAXB下载中jaxb-xjc.jar中的lib

相同的命令 - java -jar jaxb-xjc.jar fileName.xsd

当工件到位时,您可以使用它们来解组相关的xml内容。