取得具有使用Java XML解析器
问题描述:
必需属性的XML元素我有一个像取得具有使用Java XML解析器
<Parent>
<child1 key= "">
<sub children>
</child1>
<child2 key="">
<sub children>
</child2>
</parent>
XML文件在这个XML文件我想获得具有属性“关键”的所有节点。 如何使用最佳Java XML解析器实现此目的? 我尝试过使用StAX解析器,但它必须检查每个元素以检查它是否具有属性'key'。所以,在大文件的情况下输出输出需要时间。
答
的xpath用于与关键节点(空或不):
expression="//*[@key]";
,或者出于教导目的:空(@键= '')或不为空(串(@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);
+0
谢谢你的帮助。 – Rekha
根据该职位的StAX似乎是解析XML文件(https://stackoverflow.com/a/373935/6138873) – jeanr
不需要STAX的更有效的方法。使用Dom和XPath - 你会直接得到好的。 –
@jeanr StAX效率很高,但我正在为我的要求寻找更高效的方法。 – Rekha