【发布时间】:2020-07-22 04:39:14
【问题描述】:
我正在尝试做的事情的 TLDR:
-
使用 xml 文档来存储类的表示。
-
使用一些解析器类来递归文件并实例化这些类的实例。
-
我目前在获取 nodeList 的子元素(而不是孙子元素)时遇到问题。
提前致谢。
假设我有以下 xml 文档
====== data.xml ======
<document>
<tag>
<child1> some content here </child1>
<child2> some other content </child2>
</tag>
<tag>
<child1> interesting content here </child1>
<child2>
<tag>
<child1> a b c d </child1>
<child2> e f g h </child2>
</tag>
</child2>
</tag>
</document>
我尝试使用 xFile 解析器来获取所有标记节点。但是,当我执行以下操作时:
public static void parseXML() {
File file = new File("src//data//data.xml");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = null;
try {
documentBuilder = documentBuilderFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
Document doc = null;
try {
doc = documentBuilder.parse(file);
} catch (SAXException | IOException e) {
e.printStackTrace();
}
try {
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
XPathExpression expr = xPath.compile("//document//tag");
NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
System.out.println(i);
System.out.println(nodeList.item(i).getTextContent());
}
} catch (XPathExpressionException e) {
e.printStackTrace();
}
}
我得到以下输出:
0
some content here
some other content
1
interesting content here
a b c d
e f g h
2
a b c d
e f g h
如何让它只返回直接嵌套在<document> 中的<tag> 元素(因为提供给xPath.compile(String string); 的路径是//document//tag
【问题讨论】: