使用SAX解析器,如何解析java中的xml文件
问题描述:
是否可以在SAX解析器中提供路径表达式?我有一个XML文件,它具有几个相同的名称标签,但它们位于不同的元素中。有什么办法可以区分它们吗?下面是XML:使用SAX解析器,如何解析java中的xml文件
<report id="322077">
<update>
<when>1136117311</when>
<what>[email protected]</what>
</update>
<update>
<when>1136117422</when>
<what>[email protected]</what>
</update>
</report>
<report id="322074">
<update>
<when>1136117311</when>
<what>[email protected]</what>
</update>
<update>
<when>1136117422</when>
<what>[email protected]</what>
</update>
</report>
<report id="322076">
<update>
<when>1136117311</when>
<what>[email protected]</what>
</update>
<update>
<when>1136117422</when>
<what>[email protected]</what>
</update>
</report>
答
String xml= // your xml
DocumentBuilderFactory builderFactory =DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xml)));
String expression="//update"; // See XPath
XPathExpression expr = xpath.compile(expression) ;
NodeList nodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
for (int k = 0; k < nodes.getLength(); k++) {
// Do what you want with that
请参阅http://stackoverflow.com/questions/1863250/is-there-any-xpath-processor-for-sax-model – rpfun12
这是必须使用一个SAX解析器?如果首先将它读入DOM,浏览结构会更容易。然后,您可以使用许多实用方法来搜索和处理节点。 – sprinter
不是必须使用SAX解析器。我怎样才能做到这一点 – sudo