-1

I am trying to insert a new node within an exsting node for N number of times, however it is not working for me, following is what I am doing:

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.parse(filePath);
    Node pNode = doc.getElementsByTagName(parentNode).item(0);


    for (int i = 1; i <= count; i++) {
        String nodeValue = value;

        Element newNode = doc.createElement(childNode);
        newNode.appendChild(doc.createTextNode(nodeValue));
        pNode.appendChild(newNode);
            }

This is what I am trying to achieve:

<parentNode>
 <childNode> value1 </childNode>
 <childNode> value2 </childNode>
 ...
 <childNode> valueN </childNode>
</parentNode>

The name of child node is not going to change. Parent node is not a root node. Can someone please help me figure out what am I missing.

Thanks.

  • 1
    What is going wrong? Are you getting something else? What are the variables value and childNode in the for loop? – James Apr 25 '17 at 22:36

1 Answers1

0

I checked this for you, it looks like it is working as expected to me. What you have perhaps missed is that the changes to your xml are happening in memory? This is what I've done:

input xml file

<rootNode>
  <parentNode></parentNode>
</rootNode>

java test class

import java.io.IOException;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

public class DocBuilderTest {

    private String filePath = "src/test/resource/doc.xml";

    @Test
    public void builder()
        throws ParserConfigurationException, IOException, SAXException, TransformerException {
        System.out.println(processFile("parentNode", "value", "childNode"));
    }

    private String processFile(String parentNode, String value, String childNode)
        throws ParserConfigurationException, SAXException, IOException, TransformerException {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(filePath);
        Node pNode = doc.getElementsByTagName(parentNode).item(0);

        for (int i = 0; i < 5; i++) {
            String nodeValue = value + i;

            Element newNode = doc.createElement(childNode);
            newNode.appendChild(doc.createTextNode(nodeValue));
            pNode.appendChild(newNode);
        }

        return toPrettyPrintString(doc);
    }

    // From https://stackoverflow.com/a/139096/7421645
    private String toPrettyPrintString(Document doc) throws TransformerException {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        // initialize StreamResult with File object to save to file
        StreamResult result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(doc);
        transformer.transform(source, result);
        return result.getWriter().toString();
    }
}

The pretty print reference if the file is already partially indented.

and output to System.out

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<rootNode>
  <parentNode>
    <childNode>value0</childNode>
    <childNode>value1</childNode>
    <childNode>value2</childNode>
    <childNode>value3</childNode>
    <childNode>value4</childNode>
  </parentNode>
</rootNode>

NOTE This output is just printed to System.out, I've not overwritten the input file. You'd need to initialise a FileWriter to do that.

Community
  • 1
  • 1
James
  • 1,095
  • 7
  • 20
  • Thanks, this worked for me. It seems I was making changes only into memory and not writing them into file. Your code helped me. – SeleniumLearner Apr 26 '17 at 15:34