I want to add a node in the last line of an existing XML file using Java. So I have followed the code below.
Sample XML file :
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<mapping-configuration>
<fields-mapping>
<field compare="true" criteria="true" displayName="demo1"/>
<field compare="true" criteria="true" displayName="demo2"/>
</fields-mapping>
</mapping-configuration>
Code :
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File("C:/Desktop/test.xml"));
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
Node nList = doc.getDocumentElement().getChildNodes().item(0).getLastChild();
System.out.println(nList.getNodeName());
Element newserver=doc.createElement("field");
newserver.setAttribute("source", "33");
nList.appendChild(newserver).normalize();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("C:/Desktop/test.xml"));
transformer.transform(source, result);
So, I got the result as
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<mapping-configuration>
<fields-mapping>
<field compare="true" criteria="true" displayName="demo1"/>
<field compare="true" criteria="true" displayName="demo2">
<field source="33"/>
</field>
</fields-mapping>
</mapping-configuration>
But my expected Output should be
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<mapping-configuration>
<fields-mapping>
<field compare="true" criteria="true" displayName="demo1"/>
<field compare="true" criteria="true" displayName="demo2"/>
<field source="33"/>
</fields-mapping>
</mapping-configuration>