Add node to existing xml-java

I saw the same question that vb and C # are responsible for, but I need a better solution for adding nodes to xml. Did 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> 

You need to add more

 <B> <c>11<c/> <d>21<d/> <e>31<e/> </B> 
+4
source share
3 answers

XPath helps you find nodes, but not add them. I don’t think you will find it particularly useful here.

What XML interface are you using? If it is a W3C DOM (urgh), you would 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); 
+13
source

The easiest way is that you analyze, using Sax or Dom , all the files in the data structure, for example class A, which has a B class with members of class C, D, E in your case.

And bring the data structure back to XML.

+2
source

You can use XMLModier for vtd-xml to do it in a cool way, which should add the contents of the byte directly ... You just need to call XMLModier insertAfterElement () ... below is a link to a sample code: Incrementally modify XML in Java :

 import com.ximpleware.*; import java.io.*; public class ModifyXML { public static void main(String[] s) throws Exception{ VTDGen vg = new VTDGen(); // Instantiate VTDGen XMLModifier xm = new XMLModifier(); //Instantiate XMLModifier if (vg.parseFile("old.xml",false)){ VTDNav vn = vg.getNav(); xm.bind(vn); // first update the value of attr int i = vn.getAttrVal("attr"); if (i!=-1){ xm.updateToken(i,"value"); } // navigate to <a> if (vn.toElement(VTDNav.FC,"a")) { // update the text content of <a> i=vn.getText(); if (i!=-1){ xm.updateToken(i," new content "); } // insert an element before <a> (which is the cursor element) xm.insertBeforeElement("<b/>\n\t"); // insert an element after <a> (which is the cursor element) xm.insertAfterElement("\n\t<c/>"); } xm.output(new FileOutputStream("new.xml")); } } } 
0
source

All Articles