使用sax解析器解析和修改xml字符串 [英] Parsing and modifying xml string with sax parser

查看:133
本文介绍了使用sax解析器解析和修改xml字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个XML文件,我需要在其中搜索特定标记并更新它的值。问题是,使用Sax解析器是必须。我必须使用Sax Parseronly找到这些标签,dom stax j4dom dom4j解析器不在考虑范围内。

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.

我可以通过将我的xml文件转换为一个字符串并使用sax解析器解析它并通过 StringBuilder object附加新值?会没事吗?或者你会推荐什么?

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?

推荐答案

这是一个有效的代码,只需添加缺失的导入。它使用SAX并将< name> user1< / name> 更改为< name> user2< / name> 。如果您弄清楚它是如何工作的,再加上阅读SAX API,您可以对xml做任何事情。请注意,在StAX生成之前,SAX被认为是最有效的xml解析器

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

这篇关于使用sax解析器解析和修改xml字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆