使用XPath检索XML元素

时间:2012-01-12 18:31:47

标签: java xml xpath

我很难使用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。我知道我做错了什么。有人可以帮我吗?

1 个答案:

答案 0 :(得分:2)

<deviceInfo>元素的子元素包含许多仅空白文本节点。您需要对这些元素进行过滤,以便仅迭代作为元素的子元素,或者在<deviceInfo>元素中仅有空格的文本节点为ignored的模式下解析XML。