我有 JAXB 注释:
@XmlElement(name="String")
private String string = "one";
@XmlElement(name="ArrayOne")
private ArrayList<String> array1 = new ArrayList<String>();
和编码:
array.add("Just one");
JAXBContext jc1 = JAXBContext.newInstance( getClass() );
Marshaller marshaller = jc1.createMarshaller();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance() ;
Document doc = factory.newDocumentBuilder().newDocument();
marshaller.marshal(this, doc);
如果我深入研究文档节点,我看不到两者之间的任何区别 节点元素。 我的问题是,是否有任何技巧如何编码到 DOM 文档中, 该节点元素将在某种程度上不同,无论是简单对象(字符串), 或数组对象。 Marshaller 当然知道字段类型,所以我想知道, 如果它在元素数据中放置一些标志。
DOM结构是
NodeName:String NodeContent:one
NodeName:ArrayOne NodeContent:Just one
但我想要这样的:
NodeName:String NodeContent:one
NodeName:ArrayOne
Children:
NodeName:ArrayOne NodeContent:Just one
所以我知道,ArrayOne 就是数组,无论只是一个对象。
请注意,我无法更改注释,因为并不总是有可用的源。
最佳答案
您可以使用@XmlElementWrapper为集合创建包装器元素:
@XmlElement(name="String")
private String string = "one";
@XmlElementWrapper(name="ArrayOne")
private ArrayList<String> array1 = new ArrayList<String>();
此映射的 XML 输出如下所示:
<testElement>
<String>one</String>
<ArrayOne>
<array1>one</array1>
</ArrayOne>
</testElement>
评论更新: 手动在 DOM 文档上添加包装器(可能有一种更简单的方法,也许通过使用 Transformer):
TestElement te = new TestElement();
JAXBContext jc1 = JAXBContext.newInstance(TestElement.class);
Marshaller marshaller = jc1.createMarshaller();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance() ;
Document doc = factory.newDocumentBuilder().newDocument();
marshaller.marshal(te, doc);
NodeList nodeList = doc.getDocumentElement().getChildNodes();
Node newNode = doc.createElement("ArrayOneWrapper");
List<Node> arrayOneElements = new ArrayList<>();
for (int i = 0; i < nodeList.getLength(); i++) {
Node n = nodeList.item(i);
if (n.getNodeName().equals("ArrayOne")) {
arrayOneElements.add(n);
}
}
for (Node n : arrayOneElements) {
newNode.appendChild(n);
}
XML 输出:
<testElement>
<String>one</String>
<ArrayOneWrapper>
<ArrayOne>one</ArrayOne>
<ArrayOne>two</ArrayOne>
</ArrayOneWrapper>
</testElement>
关于Java JAXB 编码到 DOM 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53120588/