2

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>
0

1 Answer 1

1

In this code:

Node nList = doc.getDocumentElement().getChildNodes().item(0).getLastChild();

selects the last field element, and this:

 nList.appendChild(newserver);

adds your new element as a child of the last field element.

you want the new node as a child of the fields-mapping element, so try removing the unwanted .getLastChild().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.