如何知道标签是否包含值或其他标签? [英] How to know if a tag contains a value or another tag?

查看:162
本文介绍了如何知道标签是否包含值或其他标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在java中使用DOM表示

I am using DOM representations in java

如何区分xml标记内部是否有值或是否有其他嵌入标记?
例如,我可以:

how can I distinguish if an xml tag has a value inside it or has another embedded tag ? For example, I can have :

<item> 2 </item>

<item> <name> item1 </name> </item>

我想做以下事情

if(condition1 : there is no tags inside item tag) do ...
else  do ...

如何写条件1?

推荐答案

您可以通过迭代子节点列表来测试每个孩子:

You can just test every child by iterating over the list of child nodes:

public static boolean hasChildElements(Element el) {
    NodeList children = el.getChildNodes();
    for (int i = 0;i < children.getLength;i++) {
        if (children.item(i).getNodeType() == Node.ELEMENT_NODE) 
            return true;
        }
    }
    return false;
}

条件1是(!hasChildElements(el))

或者,您可以使用 getElementsByTagName(*)。getLength()== 0 。但是,如果子元素,此方法将遍历您正在测试的整个片段,并分配大量内存。

Alternatively, you can implement the test with getElementsByTagName("*").getLength() == 0. However, if there are sub elements, this method will traverse the whole fragment you're testing, and allocate lots of memory.

这篇关于如何知道标签是否包含值或其他标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆