我很难从使用XPath的XML文件获取XML值。 XML文件有以下模式:使用XPath检索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,这基本上是人l文件中的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'之间的关系是什么? – 2012-01-12 18:35:26
这是一个错字。儿童实际上是“名单”。 – 2012-01-12 18:49:44