您可以利用@XmlAnyElement 和XmlAnyAttribute 注释来映射额外的内容。如果您不想要 get/set 方法,只需在您的课程中添加 @XmlAccessorType(XmlAccessType.FIELD)。
客户
在下面的类中,我们映射一个特定的 XML 属性和元素,然后使用 @XmlAnyElement 注释映射可能出现的任何其他元素,并使用 @XmlAnyAttribute 映射可能出现的任何其他属性。
import java.util.*;
import javax.xml.bind.annotation.*;
import javax.xml.namespace.QName;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {
@XmlAttribute
int id;
@XmlAnyAttribute
Map<QName, String> otherAttributes;
String name;
@XmlAnyElement(lax=true)
List<Object> otherElements;
}
input.xml
我们将在演示代码中解组以下 XML 文档。
<?xml version="1.0" encoding="UTF-8"?>
<customer id="123" status="good">
<name>Jane Doe</name>
<address>
<street>1 A Street</street>
<city>Any Town</city>
</address>
<phone-number>555-1111</phone-number>
</customer>
演示
以下文档将解组 XML 输入,将所有生成的对象内容转储到 System.out 并将对象编组回 XML。
import java.io.File;
import java.util.Map.Entry;
import javax.xml.bind.*;
import javax.xml.namespace.QName;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Customer.class, Address.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum14272453/input.xml");
Customer customer = (Customer) unmarshaller.unmarshal(xml);
// Mapped XML Attribute
System.out.println("customer.id");
System.out.println(" " + customer.id);
// Other XML Attributes
System.out.println("customer.otherAttributes");
for(Entry<QName, String> entry : customer.otherAttributes.entrySet()) {
System.out.println(" " + entry);
}
// Mapped XML Element
System.out.println("customer.name");
System.out.println(" " + customer.name);
// Other XML Elements
System.out.println(customer.otherElements);
for(Object object : customer.otherElements) {
System.out.println(" " + object);
}
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(customer, System.out);
}
}
输出
以下是运行演示代码的输出,请注意所有字段是如何使用 XML 文档中的数据填充的。
customer.id
123
customer.otherAttributes
status=good
customer.name
Jane Doe
customer.otherElements
forum14272453.Address@24f454e4
[phone-number: null]
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer id="123" status="good">
<name>Jane Doe</name>
<address>
<street>1 A Street</street>
<city>Any Town</city>
</address>
<phone-number>555-1111</phone-number>
</customer>
更多信息