问题
I am trying to combine multiple xmls into one xml using DOM parser. I am fairly new to this process. I am having issue while updating the values and the order of the xml which I will be getting from JSON. Here, # of xmls to combine is equal to the # 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
}
]
}
So far I am getting the following'
<Entry>
<Person>
<Name>
<NameTitle>
<Value>Name</Value>
</NameTitle>
</Name>
<Details>
<PersonDetails>
<Name>
<NameValue/>
</Name>
</PersonDetails>
</Details>
</Person>
</Entry>
This is what is expected outcome
<Entry>
<Person>
<Details>
<PersonDetails>
<Name>
<NameValue>John Doe</NameValue>
</Name>
</PersonDetails>
</Details>
<Name>
<NameTitle>
<Value>Full Name</Value>
</NameTitle>
</Name>
</Person>
</Entry>
来源:https://stackoverflow.com/questions/56434932/retrieve-values-from-json-and-update-the-xml