user3322698
user3322698

Reputation: 265

modifing a xml file using SAX parser

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

Upvotes: 0

Views: 513

Answers (2)

vtd-xml-author
vtd-xml-author

Reputation: 3377

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");
    }
}

Upvotes: 0

Kenneth Clark
Kenneth Clark

Reputation: 1755

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?

Upvotes: 2

Related Questions