I’m having a hard time getting XML values from an XML file using XPath. 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>
What I tried to do is first of all, creating an instance of a custom class that I have made, which contains the following method:
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;
}
This method is then called with the query:
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();
Then
System.out.println("First element is "+list.item(0).getTextContent());
This has given me an empty string. Though when I try to do this:
System.out.println("First element is "+list.item(1).getTextContent());
which is basically displaying item with index “1” rather than item with index “0”, this ends up printing “device1” which is the value of the first element.
So in order to get the values of all the elements, I’d use the indices 1,3,5,7,9,11. I know I’m doing something wrong. Could anyone help me please?
The children of the
<deviceInfo>element include a number of whitespace-only text nodes. You need to filter those out so that you’re only iterating over the children that are elements, or parse the XML in a mode where white-space only text nodes inside<deviceInfo>elements are ignored.