【问题标题】:JAXB Unmarshalling of XML into HashMapJAXB 将 XML 解组为 HashMap
【发布时间】:2016-04-13 11:18:18
【问题描述】:

我有一个复杂的 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(entry,attribute) 类型。

每个条目依次具有 prioritykeypriority,我相信它们将是 HashMap (prioritykey,priority) 类型。

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

【问题讨论】:

  • 为什么选择HashMap?它不能是一个有列表/条目集的类吗?基本上我把它看作一个类结构,即 Abc 有 Pqr 列表,每个 Pqr 有一个条目列表 -> 条目有属性 -> 优先级和类 PriorityKey -> 有类和原因属性。
  • 结构需要作为 () 对访问
  • 你可以在这里使用 stax 解析器。 en.wikipedia.org/wiki/StAX
  • 属性值相同。条目键将不同。“名称”值不会有两个条目对象相同
  • @AshishPatil 它是一个配置文件,只需要通过 JAXB 处理...

标签: java xml jaxb


【解决方案1】:

在这里,首先创建合同。我创建了一个作为我学习过程的一部分...

<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 下载中的 lib 中的 jaxb-xjc.jar

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

当工件就位后,您可以使用它们来解组有问题的 xml 内容。

【讨论】:

    猜你喜欢
    • 2015-03-28
    • 1970-01-01
    • 1970-01-01
    • 2013-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-17
    • 1970-01-01
    相关资源
    最近更新 更多