如果不需要标记complement1
,2
和3
且XML可能具有complement4
,{p>如何使用JAXB来序列化和反序列化以下XML? {1}},5
?
我考虑过使用n
注释,但我需要知道值“First”属于第一个补码,“Second”属于第二个等等。
@XmlAnyElement
答案 0 :(得分:5)
我相信您可以使用@XmlAnyElement,并且您可以访问元素名称
您需要使用“任何列表”构造
当JAXB解组XML时,您将拥有一个DOM Element对象列表,每个对象都包含元素名称和内容。
我认为您必须手动强制执行每个元素标记名称与“complementN”模式匹配。
e.g。这是从一个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