是否可以解析 XML 并获取所有叶节点?
<root>
<emp>
<name>abc<name>
<age>12</age>
</emp>
<dept>
<branch>cse</branch>
</dept>
</root>
我的输出应该是 姓名 年龄 分支机构
最佳答案
使用此 XPath 表达式查找没有其他元素作为子元素的所有元素://*[count(./*) = 0]
。
try {
final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("input.xml");
final XPathExpression xpath = XPathFactory.newInstance().newXPath().compile("//*[count(./*) = 0]");
final NodeList nodeList = (NodeList) xpath.evaluate(doc, XPathConstants.NODESET);
for(int i = 0; i < nodeList.getLength(); i++) {
final Element el = (Element) nodeList.item(i);
System.out.println(el.getNodeName());
}
} catch (Exception e) {
e.printStackTrace();
}
结果是
name
age
branch
关于java - 获取叶节点 - Java 中的 XML 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20783506/