Uvais Ibrahim Uvais Ibrahim - 3 months ago 13
Java Question

Java code to insert new elements to inner child nodes

I have an XML document as given below.

<rootElement>
<fisrtElement>
<firstElementChild>
<child1>A</child1>
<child2>B</child2>
</firstElementChild>
</fisrtElement>
</rootElement>


Now I need to add a child node,
<child3>C</child3>
, into this XML document so that my final XML document will look like below.

<rootElement>
<fisrtElement>
<firstElementChild>
<child1>A</child1>
<child2>B</child2>
<child3>C</child3>
</firstElementChild>
</fisrtElement>
</rootElement>


I need a Java code for this. I have searched google and now I know how to add elements to root element using
DocumentBuilderFactory
. But I don't how to do it for inner nodes as I given above. Please advice.

Edit

I have tried the below snippent for adding new element.

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new File("./sample.xml"));

Element itemNode = doc.createElement("child3");
itemNode.appendChild(doc.createTextNode("C"));
Node channelNode = doc.getElementsByTagName("channel").item(0);
channelNode.appendChild(itemNode);


And the output is something like below.

<rootElement>
<fisrtElement>
<firstElementChild>
<child1>A</child1>
<child2>B</child2>
<child3>c</child3>
</firstElementChild>
</fisrtElement>
</rootElement>


and when I ran the code again with the modification given below,

Element itemNode = doc.createElement("child4");
itemNode.appendChild(doc.createTextNode("D"));


The third child node
<child3>C</child3>
is getting replaced with the fourth child
<child4>D</child4>
. What I need is incrementally adding child nodes for
<firstElementChild>
. What I am missing here. Please give an advice. Thanks in advance.

Answer

You should use this method on your firstElementChild node :

Comments