我想修改 JAXB 编码操作的输出流以包含一些任意 XML。这是一个说明情况的示例。
我有一个任意的 Product
带有 JAXB 注释的域对象,当前看起来像这样:
@XmlRootElement(name="Product")
public class Product {
@XmlElement(name="CommonProperty")
private String commonProperty="Something";
@XmlElement(name="ExtraXml")
private String extraXml="Something extra";
}
这通常会编码为:
<Product>
<CommonProperty>Something</CommonProperty>
<ExtraXml>Something else</ExtraXml>
</Product>
现在,如果 extraXml
会怎样?字段包含一些额外的 XML(具有任意复杂性),这些 XML 将与最终编码结果内联?
比如说,extraXml
包含“<abc><def>Something extra</def></abc>
”,我真的很想要一个使我能够编码 Product
的解决方案像这样(格式可选):
<Product>
<CommonProperty>Something</CommonProperty>
<abc>
<def>Something extra</def>
</abc>
</Product>
我看过this related question但它并没有完全产生我想要的结果,因为它似乎更适合整体格式更改而不是 DOM 插入。
extraXml
属性只是为了说明,它可以标记为 @XmlTransient
或进入一个专门的类(class)。唯一的标准是它可以以某种方式获得 String
包含完全任意的 XML 内容以附加到个人 Product
编码输出。
我还应该提到,此输出的消费者能够以适合他们的方式解析任意内容。这里的目的是简化服务器端的处理。
在此先感谢您提供的任何帮助。
最佳答案
您可以将额外的 XML 表示为 DOM 节点而不是字符串。
将 extraXML 属性更改为 org.w3c.dom.Node 而不是 String,并使用 @XmlAnyElement 对其进行注释。
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.w3c.dom.Node;
@XmlRootElement(name="Product")
@XmlAccessorType(XmlAccessType.FIELD)
public class Product {
@XmlElement(name="CommonProperty")
private String commonProperty="Something";
@XmlAnyElement
private Node extraXml;
}
然后当您编码 XML 文档时,例如:
<Product>
<CommonProperty>Something</CommonProperty>
<abc>
<def>Something extra</def>
</abc>
</Product>
使用以下代码:
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Product.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("input.xml");
Product product = (Product) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(product, System.out);
}
}
“额外的 XML”将保留为 DOM 节点。
关于java - 如何修改 JAXB 编码输出流以包含任意内联 XML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4224544/