I m 很难从使用XPath的XML档案中获取XML数值。 The XML file has the following schema:
<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");
So far so good, for this is returning a NodeList with length 2, which is basically all the deviceInfo elements in the file. What I wish to do next is iterating over each deviceInfo in order to get the value of its children (deviceId,macAddress,deviceType,deviceClass,location,productionState).
I tried to do the following:
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。 我知道我做的是错事。 谁能帮助我?