java 使用 sax 解析器解析和修改 xml 字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13687799/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parsing and modifying xml string with sax parser
提问by user1873190
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 解析器是“必须的”。我必须“仅”使用 Sax Parser 来找到这些标签,dom stax j4dom dom4j 解析器不在考虑范围内。
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?
我可以通过将我的 xml 文件转换为字符串并使用 sax 解析器解析它并按StringBuilder
对象附加新值来完成此任务吗?会好吗?或者你会推荐什么?
回答by Evgeniy Dorofeev
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
这是一个工作代码,只需添加缺少的导入。它使用 SAX 并更改<name>user1</name>
为<name>user2</name>
. 如果您弄清楚它是如何工作的并阅读 SAX API,您就可以对您的 xml 做任何事情。请注意,在 StAX 出现之前,SAX 一直被认为是最高效的 xml 解析器
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);
}
回答by CodeDreamer
SAX parser is not a bad choice if time is not a consideration and memory is.
如果时间不是考虑因素而内存是,SAX 解析器不是一个糟糕的选择。