Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have an XML file, I need to search for a specific tag in it and update it's value. The problem is that, using Sax parser is "must". I have to find these tags by using Sax Parser "only", dom stax j4dom dom4j parsers are out of consideration.

Can I accomplish this task by converting my xml file to a string and parse it by using sax parser and append the new value by StringBuilder object? Would it be okay? Or what would you recommend?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
306 views
Welcome To Ask or Share your Answers For Others

1 Answer

This is a working code, just add missing imports. It uses SAX and changes <name>user1</name> to <name>user2</name>. If you figure out how it works plus read SAX API you can do anything with your xml. Note that SAX had been considered the most efficient xml parser until StAX came into being

public static void main(String[] args) throws Exception {
    String xml = "<users><user><name>user1</name></user></users>";
    XMLReader xr = new XMLFilterImpl(XMLReaderFactory.createXMLReader()) {
        private String tagName = "";
        @Override
        public void startElement(String uri, String localName, String qName, Attributes atts)
                throws SAXException {
            tagName = qName;
            super.startElement(uri, localName, qName, atts);
        }
        public void endElement(String uri, String localName, String qName) throws SAXException {
            tagName = "";
            super.endElement(uri, localName, qName);
        }
        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
            if (tagName.equals("name")) {
                ch = "user2".toCharArray();
                start = 0;
                length = ch.length; 
            }
            super.characters(ch, start, length);
        }
    };
    Source src = new SAXSource(xr, new InputSource(new StringReader(xml)));
    Result res = new StreamResult(System.out);
    TransformerFactory.newInstance().newTransformer().transform(src, res);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...