【问题标题】:Get XML Node with id or name获取带有 id 或 name 的 XML 节点
【发布时间】:2020-06-16 17:03:56
【问题描述】:

我有以下 xml 文件

<Capabilities>
    <Capability id="test" name="test">
       <File Path="bin/test.exe" />
       <File Path="bin/abc.dll" />
       <File Path="bin/xyz.dll" />
       <File Path="LICENSE" />
       <File Path="third-party-programs.txt" />
    </Capability>
    <Capability id="test1" name="test1">
       <File Path="bin/test1.exe" />
       <File Path="LICENSE" />
       <File Path="third-party-programs.txt" />
    </Capability>
<Capabilities>

我想获取 id="test1" 的节点,但不遍历所有节点。 我尝试在 java 中使用以下内容

try {
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        document = documentBuilder.parse(xmlFile);
    } catch (ParserConfigurationException | SAXException | IOException e) {
        e.printStackTrace();
    }
    // get the node with id="test1"
    Node capabilityNode = document.getElementById("test1");

从上面的代码我得到空值。 getElementbyId 文档说 id 属性必须具有类型 ID。如何确保 id 是 ID 类型,或者有没有办法可以直接获取节点而无需按名称循环?

谢谢

【问题讨论】:

  • getElementById 是否在 java 中?
  • 是的,它在 java 中
  • 一个属性可以通过为文档定义一个这样的DTD来由类型ID组成。否则,您将需要循环。
  • 我该如何做那个 DTD?

标签: java xml dom xml-parsing


【解决方案1】:

您可以使用XPath 编写自定义getElementById。 此函数将返回第一个具有属性id 且值为idValue 的元素。

public static Node getElementById(Document document, String idValue) throws XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    return (Node) xpath.evaluate(String.format("//*[@id='%s']", idValue), document, XPathConstants.NODE);
}

【讨论】:

    【解决方案2】:

    好的,首先你在最后一个标签中缺少右斜杠。 第二件事是,如果您想获取某些元素的属性,您可以使用 (Element) 类型从您想要的节点中检索属性 观察。这个解决方案只会循环两次,而不是遍历所有标签

        NodeList nodeList = doc.getElementsByTagName("Capability");
        String nodeAttribute ="";
        for(int i =0;i<nodeList.getLength();i++){
            nodeAttribute = ((Element) nodeList.item(i)).getAttribute("id");
            if(nodeAttribute.equals("test1"))
                break;
        }
    
        System.out.println("nodeAttribute:"+nodeAttribute+ " Node 
        Length:"+nodeList.getLength()); 
    

    【讨论】:

    • 这是不正确的。标签名是Capabilityid是一个属性名。
    • 是的,对不起,我的错误,已修复
    • 但这仍然不是 OP 想要的。它只会得到所有 Capability 元素的列表,而 OP 想要一个精确的 Capability 元素和 id="test1"
    猜你喜欢
    • 2013-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多