4

我如何使用 JAXB 序列化和反序列化以下 XML,考虑到标签和不是必需的,并且 XML 可能complement1有, , ?23complement45n

我考虑过使用@XmlAnyElement注释,但我需要知道值“First”属于第一个补码,“Second”属于第二个补码,等等。

<resource>
    <id>Identifier</id>
    <name>Name</name>
    <complement1>First</complement1>
    <complement2>Second</complement2>
    <complement3>Third</complement3>
</resource>
4

1 回答 1

6

我相信您可以使用@XmlAnyElement,并且您确实可以访问元素名称。
您需要使用“任何列表”构造。
当 JAXB 解组 XML 时,您将拥有一个 DOM Element 对象列表,每个对象都包含元素名称和内容。
我认为您必须手动强制每个元素标签名称与“complementN”模式匹配。

例如,这是从 Oracle 示例之一修改的:

架构:

<xs:element name="person">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="firstname" type="xs:string"/>
      <xs:element name="lastname" type="xs:string"/>
      <xs:sequence>
          <xs:any minOccurs="0" maxOccurs="unbounded"/>
      </xs:sequence>
    </xs:sequence>
  </xs:complexType>
</xs:element> 

xjc 生成的 Person 类的片段:

...
@XmlRootElement(name = "person")
public class Person {

    @XmlElement(required = true)
    protected String firstname;
    @XmlElement(required = true)
    protected String lastname;
    @XmlAnyElement(lax = true)
    protected List<Object> any;
...

测试 XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<person>
  <firstname>David</firstname>
  <lastname>Francis</lastname>
  <anyItem1>anyItem1Value</anyItem1>
  <anyItem2>anyItem2Value</anyItem2>
</person>

测试类:

JAXBContext jc = JAXBContext.newInstance( "generated" );
Unmarshaller u = jc.createUnmarshaller();
Person contents = (Person) u.unmarshal(Testit.class.getResource("./anysample_test1.xml"));
System.out.println("contents: " + contents);
System.out.println("  firstname: " + contents.getFirstname());
System.out.println("  lastname: " + contents.getLastname());
System.out.println("  any: ");
for (Object anyItem : contents.getAny()) {
    System.out.println("    any item: " + anyItem);
    Element ele = (Element) anyItem;
    System.out.println("      ele name: " + ele.getTagName());
    System.out.println("      ele text content: " + ele.getTextContent());
}

输出:

contents: generated.Person@1bfc93a
  firstname: David
  lastname: Francis
  any: 
    any item: [anyItem1: null]
      ele name: anyItem1
      ele text content: anyItem1Value
    any item: [anyItem2: null]
      ele name: anyItem2
      ele text content: anyItem2Value
于 2012-05-17T15:03:24.477 回答