我相信您可以使用@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