如何知道一个标签是否包含一个值或另一个标签?

SLA*_*SLA 5 java xml dom

我在 Java 中使用 DOM 表示

我如何区分 xml 标签内部是否有值或是否有另一个嵌入标签?例如,我可以有:

<item> 2 </item>
Run Code Online (Sandbox Code Playgroud)

或者

<item> <name> item1 </name> </item>
Run Code Online (Sandbox Code Playgroud)

我想做以下事情

if(condition1 : there is no tags inside item tag) do ...
else  do ...
Run Code Online (Sandbox Code Playgroud)

我怎么写条件1?

phi*_*hag 4

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

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;
}
Run Code Online (Sandbox Code Playgroud)

条件 1 则为(! hasChildElements(el))

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