Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append node to an existing xml-Java

Tags:

java

xml

I have seen the same question being answered for vb and c#, but i need a Java best solution for appending nodes to an xml. Will xpath help? I have

<A>
  <B>
    <c>1<c/>
    <d>2<d/>
    <e>3<e/>
  </B>
  <B>
    <c>1<c/>
    <d>2<d/>
    <e>3<e/>
  </B>
</A>

Need to append another

<B>
   <c>11<c/>
   <d>21<d/>
   <e>31<e/>
</B>
like image 317
Ajay Avatar asked Dec 07 '22 06:12

Ajay


2 Answers

XPath will help you to find nodes, but not really append them. I don't think you'd find it particularly useful here.

Which XML API are you using? If it's the W3C DOM (urgh) then you'd do something like:

Element newB = document.createElement("B");
Element newC = document.createElement("c");
newC.setTextContent("11");
Element newD = document.createElement("d");
newD.setTextContent("21");
Element newE = document.createElement("e");
newE.setTextContent("31");
newB.appendChild(newC);
newB.appendChild(newD);
newB.appendChild(newE);
document.getDocumentElement().appendChild(newB);
like image 192
Jon Skeet Avatar answered Dec 20 '22 16:12

Jon Skeet


The most strait-forward way is that you parse, using Sax or Dom, all the files into a data structure, for example an A class which has a B class with members of C,D,E class in your case.

And output the data structure back to XML.

like image 44
Winston Chen Avatar answered Dec 20 '22 18:12

Winston Chen