草庐IT

Java DOM : How to get how many child elements

coder 2024-06-27 原文

我有一个 XML 文档:

<entities xmlns="urn:yahoo:cap">
    <entity score="0.988">
        <text end="4" endchar="4" start="0" startchar="0">Messi</text>
        <wiki_url>http://en.wikipedia.com/wiki/Lionel_Messi</wiki_url>
        <types>
            <type region="us">/person</type>
        </types>
    </entity>
</entities>

我有一个 TreeMap<String,String> data其中存储 getTextContent()对于 "text""wiki_url"元素。一些"entity" s 将只有 "text"元素(没有 "wiki_url" )所以我需要一种方法来找出何时只有文本元素作为子元素以及何时有 "wiki_url" .我可以使用 document.getElementByTag("text") & document.getElementByTag("wiki_url")但那样我就会失去文本和 url 之间的关系。

我正在尝试获取 "entity" 中的元素数量元素使用:

NodeList entities = document.getElementsByTagName("entity"); //List of all the entity nodes
int nchild; //Number of children
System.out.println("Number of entities: "+ entities.getLength()); //Prints 1 as expected
nchild=entities.item(0).getChildNodes().getLength(); //Returns 7

然而,如上所示,这将返回 7(我不明白,如果包括孙子,它肯定是 3 或 4) 然后我打算使用 child 的数量循环遍历所有 child 以检查是否 getNodeName().equals("wiki_url")如果正确,将其保存到数据中。

当我只能数出 3 个 child 和 1 个孙子时,为什么我得到的 child 数是 7?

最佳答案

> 之后的空格的 <entity score="0.988">也计算节点,类似地,标签之间的行尾字符也被解析为节点。如果您对具有名称的特定节点感兴趣,请添加如下所示的辅助方法并在您需要的任何地方调用。

Node getChild(final NodeList list, final String name)
    {
        for (int i = 0; i < list.getLength(); i++)
        {
            final Node node = list.item(i);
            if (name.equals(node.getNodeName()))
            {
                return node;
            }
        }
        return null;
    }

然后打电话

final NodeList childNodes = entities.item(0).getChildNodes();
final Node textNode = getChild(childNodes, "text");
final Node wikiUrlNode = getChild(childNodes, "wiki_url");

通常在使用 DOM 时,会想出像上面这样的辅助方法来简化主要处理逻辑。

关于Java DOM : How to get how many child elements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17278961/

有关Java DOM : How to get how many child elements的更多相关文章

随机推荐