【发布时间】:2012-01-12 18:31:46
【问题描述】:
我很难使用 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。我知道我做错了什么。谁能帮帮我?
【问题讨论】:
-
list和children和nodes是什么关系? -
那是一个错字。 Children实际上是“列表”。