我有一个 XML 文件,我需要在其中搜索特定标签并更新它的值。问题在于,使用 Sax 解析器是“必须”的。我必须“仅”使用 Sax 解析器来找到这些标签,不考虑 dom stax j4dom dom4j 解析器。
我能否通过将我的 xml 文件转换为字符串并使用 sax 解析器解析它并通过 StringBuilder
对象附加新值来完成此任务?会好吗?或者您会推荐什么?
最佳答案
这是一个工作代码,只需添加缺少的导入。它使用 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);
}
关于java - 使用 sax 解析器解析和修改 xml 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13687799/