【问题标题】:How get tag value using DOM parser如何使用 DOM 解析器获取标签值
【发布时间】:2013-06-10 10:33:33
【问题描述】:

我在我的应用程序中使用 dom 解析器。所以。我有下一个情况:

XML:

<test>
    <A>
      <B>hello</B>
    world
    </A>
</test>

代码:

private TagA parseTagA(Node node) {
        TagA tagA = new TagA();
        if (node.hasChildNodes()) {
            NodeList childList = node.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                // gets child
                Node child = childList.item(i);
                // parse <B> tag
                if (child != null && "B".equals(child.getNodeName())) {
                   tagA.setTagB(parseTagB(child));
                }
            }
        }

        String tagABody = node.getTextContent();
        tagA.setBody(tagABody);


        return tagA;
    }

我使用 node.getTextContent() 方法来获取标签 A 的值,但我也得到标签 B 的值。我的意思是“tagABody”的值是“hello world”,但应该只是“world”。方法 getNodeValue() 返回 null,我猜是因为节点类型是 ELEMENT_NODE。无论如何我有一个问题:我如何才能获得标签 A 的价值,只有“世界”?谢谢。

【问题讨论】:

  • 您的 A 节点有两个子节点,一个 B 节点和一个文本节点。您可以测试循环中节点的类型,或者通常文本节点的节点名是#text

标签: java dom xml-parsing domparser


【解决方案1】:

我没有测试它,但我相信下面的代码应该可以工作:

private TagA parseTagA(Node node) {
    TagA tagA = new TagA();
 String tagABody  = "";
    if (node.hasChildNodes()) {
        NodeList childList = node.getChildNodes();
        for (int i = 0; i < childList.getLength(); i++) {
            // gets child
            Node child = childList.item(i);
        if(child.getNodeType == Node.TEXT_NODE) {
           tagABody = node.getNodeValue();
           tagA.setBody(tagABody);
            } else
            // parse <B> tag
            if (child != null && "B".equals(child.getNodeName())) {
               tagA.setTagB(parseTagB(child));
            }
        }
    }


    return tagA;
}

【讨论】:

  • 非常感谢您将答案标记为已接受,如果它解决了您的问题。谢谢
【解决方案2】:

我建议处理 A 元素的文本节点子节点。

无论如何,您都可以在子节点的循环中执行此操作。为您识别标签Bif 将有一个else,您将在其中累积非B 文本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 1970-01-01
    • 2012-10-05
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多