[英]JAXB unmarshal part of XML into classes and leave rest as Element or Node
Is there a way to unmarshal a XML document partially into Java classes (eg up to a certain depth), and leave the rest as Nodes or Elements (or even XML String or Document), accessible from the unmarshalled part. 有没有办法将XML文档部分解组到Java类中(例如,直到某个深度),并将其余部分保留为节点或元素(甚至XML字符串或文档),可以从未编组的部分访问。
Eg I have an XML: 我有一个XML:
<customer>
<name>Mike</name>
<items>
<item>Car</item>
<item>Boat</item>
</items>
</customer>
And Java class: 和Java类:
@XmlRootElement
public class Customer {
@XmlElement
private String name;
// something like this:
private Node items;
// or like this:
// private String items;
}
The reason is because I'm not interested in the items
part, I will never parse or access it in Java. 原因是因为我对
items
部分不感兴趣,我将永远不会在Java中解析或访问它。 But I need to be able to save it and later retrieve it and generate a full XML document. 但我需要能够保存它,然后检索它并生成一个完整的XML文档。 The
name
element on the other hand I will use in Java code. 另一方面,我将在Java代码中使用
name
元素。
I want that the schema of the items
part (at least the sub-elements) can be changed without me having to change the Java classes. 我希望可以更改
items
部分的模式(至少是子元素),而不必更改Java类。
You can use @XmlAnyElement(lax=true)
to handle this use case. 您可以使用
@XmlAnyElement(lax=true)
来处理此用例。 This annotation allows you to unmarshall any XML to a Java object (DOM Node). 此批注允许您将任何XML解组为Java对象(DOM节点)。
@XmlRootElement(name = "customer")
public class Customer {
@XmlElement
private String name;
@XmlAnyElement(lax=true)
private Object items;
}
The marshaller will write the XML nodes properly 编组器将正确编写XML节点
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) jaxbUnmarshaller.unmarshal(reader);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(customer, System.out);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.