我有像
这样的XML文件 <Parent>
<child1 key= "">
<sub children>
</child1>
<child2 key="">
<sub children>
</child2>
</parent>
在这个XML文件中,我想获得所有具有属性&#39; key&#39;的节点。 如何使用最佳Java XML Parser实现这一目标? 我尝试使用StAX解析器,但它必须检查每个元素以检查它是否具有属性&#39; key&#39;或不。因此,在大文件的情况下提供输出需要时间。
答案 0 :(得分:0)
带键的节点的xpath(空或不):
expression="//*[@key]";
或者,为了说明目的:清空(@ key =&#39;&#39;)或不清空(字符串(@key))
expression="//*[(@key='')or(string(@key))]";
要解析DOM,国外有很多例子。
标准代码:
DocumentBuilderFactory builderFactory =DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xml)));
XPath xpath = XPathFactory.newInstance().newXPath();
String expression="//*[(@key='')or(string(@key))]";
Set<String> towns=new HashSet<String>();
XPathExpression expr = xpath.compile(expression) ;
NodeList nodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET);