0

Can we modify or update xml file using SAX parser. If yes, please provide me the sample code or any helpful link

my xml file looks like this

<vertices>
<vertex>
<name>user1</name>
<type>Ashok</type>
<nickname>nickuser1</nickname>
</vertex>
</vertices>"

I want to change "user1" to say "user2". Help me out

user3322698
  • 265
  • 1
  • 5
  • 19
  • 1
    You have many options , modifying the XML its best suited for a dom parser. Sax is intended for quick read access with minimal memory overhead , not for writing documents. http://www.mkyong.com/java/how-to-modify-xml-file-in-java-dom-parser/ http://stackoverflow.com/questions/12459712/modify-xml-file-with-xpath – Kenneth Clark May 09 '14 at 08:39
  • This question helped me with the same issue http://stackoverflow.com/questions/13687799/parsing-and-modifying-xml-string-with-sax-parser – a.hrdie May 09 '14 at 08:43
  • @ Kenneth Clark if I use DOM entire xml file will be loaded that should not happen in my case. And does this xpath load the entire xml file? – user3322698 May 09 '14 at 08:56
  • @ a.hrdie: this link produces the updated result but I want to put the updated result into the same xml file. – user3322698 May 09 '14 at 09:05

2 Answers2

2

If you are reluctant to use a DOM parser because you have a large XML you can use the XPATH or XLST to transform the xml.

What is best way to change one value in XML files in Java?

Community
  • 1
  • 1
Kenneth Clark
  • 1,725
  • 2
  • 14
  • 26
0

Below is the code to do it in vtd-xml... It is a lot more efficient/simpler than DOM or SAX based solutions... for further reading here is an article entitled manipulate XML the Ximple Way...

import java.io.*;
public class modifyXML {
    public static void main(String[] s) throws VTDException, IOException{
        VTDGen vg = new VTDGen();
        if (!vg.parseFile("input.xml", false))
            return;
        VTDNav vn = vg.getNav();
        AutoPilot ap = new AutoPilot(vn);
        ap.selectXPath("/vertices/vertex/name/text()");
        XMLModifier xm = new XMLModifier(vn);
        // using XPath
        int i=ap.evalXPath();
        if(i!=-1){
            xm.updateToken(i, "user2");
        }
        xm.output("output.xml");
    }
}
vtd-xml-author
  • 3,319
  • 4
  • 22
  • 30