java - 使用 XPath 检索 XML 元素

标签 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。我知道我做错了什么。谁能帮帮我?

最佳答案

<deviceInfo> 的 children 元素包括许多纯空白文本节点。您需要过滤掉那些,以便您只迭代作为元素的子元素,或者以一种模式解析 XML,其中空白文本节点在 <deviceInfo> 中。元素是 ignored .

关于java - 使用 XPath 检索 XML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8840356/

相关文章:

java.lang.IllegalStateException : Could not find method btnSubmit(View) in a parent or ancestor Context for android:onClick

java - 当用户尝试使用 JavaFx 中的 setOnCloseRequest 关闭应用程序时的警告框

java - 如何在TabLayout中包裹单个选项卡宽度?

python - Minidom(XML解析)与Python - 不想获取任何 child 的子节点

c# - VS 2015 智能感知 : Exceptions Thrown not Previewed

css - 如何获取包裹在 <p> 标签下的段落中的文本的 CSS 选择器

java - 撒克逊 + Spring - IllegalArgumentException : Unknown Attribute http://java. sun.com/xml/jaxp/properties/schemaLanguage

java - 将带有负数和小数的字符串转换为 int?

java - 我可以将扩展对象与其扩展的对象一起放入 java 的列表中吗?

python - Selenium,Xpath,选择节点内文本的特定部分