Reputation: 741
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.
Upvotes: 0
Views: 2565
Reputation: 4558
You should use this method on your firstElementChild
node :
appendChild
: http://docs.oracle.com/javase/8/docs/api/org/w3c/dom/Node.html#appendChild(org.w3c.dom.Node)Upvotes: 1