我很难使用 XPath 从 XML 文件中获取 XML 值。 XML 文件具有以下架构:
<devicesInfo>
<deviceInfo>
<deviceId>device1</deviceId>
<macAddress>00:21:85:C9:19:A4</macAddress>
<deviceType>deviceType1</deviceType>
<deviceClass>/Server/SSH/Linux/</deviceClass>
<location>location1</location>
<productionState>Decommissioned</productionState>
</deviceInfo>
<deviceInfo>
<deviceId>device2</deviceId>
<macAddress>00:21:85:C9:19:F5</macAddress>
<deviceType>deviceType1</deviceType>
<deviceClass>/Server/SSH/Linux/</deviceClass>
<location>location1</location>
<productionState>Decommissioned</productionState>
</deviceInfo>
</devicesInfo>
我尝试做的是首先创建一个自定义类的实例,其中包含以下方法:
public NodeList getNodesList(String xmlQuery) throws XPathExpressionException {
NodeList nodes = null;
try {
nodes = (NodeList) xPath.evaluate(xmlQuery, doc, XPathConstants.NODESET);
} catch (XPathExpressionException ex) {
throw ex;
}
return nodes;
}
然后使用查询调用此方法:
NodeList nodes = xmlHandler.getNodesList("/devicesInfo/deviceInfo");
到目前为止一切顺利,因为它返回了一个长度为 2 的 NodeList,它基本上是文件中所有的 deviceInfo 元素。 接下来我想做的是遍历每个 deviceInfo 以获得其子项的值(deviceId、macAddress、deviceType、deviceClass、location、productionState)。
我尝试执行以下操作:
NodeList list = nodes.item(0).getChildNodes();
然后
System.out.println("First element is "+list.item(0).getTextContent());
这给了我一个空字符串。虽然当我尝试这样做时:
System.out.println("First element is "+list.item(1).getTextContent());
基本上显示索引为“1”的项目而不是索引为“0”的项目,这最终打印“device1”,这是第一个元素的值。
因此,为了获得所有元素的值,我将使用索引 1、3、5、7、9、11。我知道我做错了什么。谁能帮帮我?
最佳答案
<deviceInfo>
的 children 元素包括许多纯空白文本节点。您需要过滤掉那些,以便您只迭代作为元素的子元素,或者以一种模式解析 XML,其中空白文本节点在 <deviceInfo>
中。元素是 ignored .
关于java - 使用 XPath 检索 XML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8840356/