【问题标题】:How to find a child element with specific attribute value如何找到具有特定属性值的子元素
【发布时间】:2013-12-10 04:57:39
【问题描述】:

我习惯用 C++ 库进行 xml 解析,即 rapidxml 和 tinyxml。内置 DOM 解析器的 java 对我来说完全没有意义。经过一番努力,我能够存储我需要的根节点,但现在我想找到一个具有特定 id 的标签。

这是一个示例 xml:

<?xml version="1.0" encoding="UTF-8"?>
<adventure title="Test Adventure" author="Tester">
    <enemies>
        <enemy id="e1" difficulty="1">Enemy1</enemy>
    </enemies>
    <story>
        <narration id="n1" action="d1">It's adventure time!</narration>
        <decision id="d1">
            <description>Would you like to participate?</description>
            <choice action="n2">Yes, please.</choice>
            <choice action="n3">Not the slightest.</choice>
        </decision>
        <narration id="n2" action="end">Great choice!</narration>
        <narration id="n3" action="end">Okay...</narration>
    </story>
</adventure>

我将&lt;story&gt; 节点存储在Node 实例中。从那里,我想找到具有特定 id 的节点(比如说“n3”节点)。

我想用这个方法:

private Node findNode(String id) {
    Node node = storyNode.getFirstChild();
    while ( node != null ) {
        Element elem = (Element)node;
        if ( elem.getAttribute("id") == id ) {
            return node;
        }
        node = node.getNextSibling();
    }

    return null;
}

这将是我使用 C++ 库的方式,但这离工作还很远……我不明白为什么我必须为如此简单的任务进行类型转换。为什么Node 不能通过指定属性名称来获取属性。 getFirstChild() 似乎甚至没有返回第一个孩子......

我在网上找到的包装类要么有 30 个循环深度,要么更难使用。为什么这么复杂?我做错了什么?

【问题讨论】:

  • 奇怪的是,它与 .Net 库中的实现非常相似,所以我认为它是基于标准机构的建议,他们可能设计了解决方案并且从未使用过......
  • @MadProgrammer 真的很疯狂。 NodeLists 您必须遍历它,但不能使用迭代器,因为取出节点的唯一方法是使用 .item(index) 方法,该方法返回 Node,可能成为Element,它会一直持续下去......我需要三种方法,一种可以抓取下一个兄弟元素,一种用于返回特定的子元素,或者第一种方法,如果它在没有参数的情况下被调用,第三个读取特定属性。如果我愿意,我不能让这变得更困难,这里确实有问题。
  • 就个人而言,我写了一个小库来“包装”这种疯狂......是的,我什至写了一个IterableNodeList......我的直觉是它是由工程师设计和编写的。 ..在纸上很棒...对于实际必须使用它的人来说不是那么多;)

标签: java xml parsing dom


【解决方案1】:

为什么 API 如此...很棒...将归结为它的设计原因和方式。解决方案,可能比你想象的更简单。

您可以使用的功能之一是 XPath 实现,它被吹捧为 XML 的查询语言。

因此,您可以简单地使用//*[@id='n1'] 之类的东西来查找具有等于n1 的id 属性的任何节点,而不是尝试循环遍历每个节点和每个子节点(例如)。

使用您的示例 XML 和以下代码...

try {
    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File("Test.xml"));
    Node root = doc.getDocumentElement();

    XPath xPath = XPathFactory.newInstance().newXPath();

    XPathExpression xExpress = xPath.compile("//*[@id='n1']");
    NodeList nl = (NodeList)xExpress.evaluate(root, XPathConstants.NODESET);

    System.out.println("Found " + nl.getLength() + " matches");
} catch (SAXException | IOException | ParserConfigurationException | XPathExpressionException ex) {
    ex.printStackTrace();
}

这个输出了

Found 1 matches

查看XPath了解更多详情

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-03
    • 2021-06-30
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    • 2013-04-24
    • 1970-01-01
    • 2016-02-13
    相关资源
    最近更新 更多