我正在尝试使用DOM解析器将多个xml合并为一个xml。我对这个过程还很陌生。我在更新JSON的值和xml的顺序时遇到问题。在这里,要组合的xml数量等于json。
Document outputDoc = db.parse(baseXml);
Node outputNode = outputDoc.getElementsByTagName("Entry").item(0);
for (String inputXml : inputXmls) {
Document inputDoc = db.parse(inputXml);
inputDoc.normalize();
NodeList nodeList = inputDoc.getElementsByTagName("Person");
for (int i = 0; i < nodeList.getLength(); i++) {
Node copiedNode = outputDoc.importNode(nodeList.item(i),true);
outputNode.appendChild(copiedNode);
}
}
processXml(outputDoc, file);
}
private static void processXml(Document xml, File file) throws TransformerException {
Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.INDENT, "yes");
tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
DOMSource source = new DOMSource(xml);
StreamResult result = new StreamResult(file);
tf.transform(source, result);
}
Base.xml
<?xml version="1.0" encoding="utf-8" ?>
<Entry>
</Entry>
xml1.xml
<?xml version="1.0" encoding="utf-8" ?>
<Entry>
<Person>
<Name>
<NameTitle>
<Value>Name</Value>
</NameTitle>
</Name>
<Details>
<PersonDetails>
<Name>
<NameValue></NameValue>
</Name>
</PersonDetails>
</Details>
</Person>
</Entry>
json1.json
{
"id": 1,
"json": [
{
"nameTitle": "Full Name",
"displayOrder": 2
},
{
"nameValue": "John Doe",
"displayOrder": 1
}
]
}
到目前为止,我得到以下内容'
<Entry>
<Person>
<Name>
<NameTitle>
<Value>Name</Value>
</NameTitle>
</Name>
<Details>
<PersonDetails>
<Name>
<NameValue/>
</Name>
</PersonDetails>
</Details>
</Person>
</Entry>
这是预期的结果
<Entry>
<Person>
<Details>
<PersonDetails>
<Name>
<NameValue>John Doe</NameValue>
</Name>
</PersonDetails>
</Details>
<Name>
<NameTitle>
<Value>Full Name</Value>
</NameTitle>
</Name>
</Person>
</Entry>