我正在使用java中的DOM表示法如何知道标签是否包含值或其他标签?
如何区分xml标记是否具有值或具有其他嵌入标记? 例如,我可以有:
<item> 2 </item>
或
<item> <name> item1 </name> </item>
我想要做的
if(condition1 : there is no tags inside item tag) do ...
else do ...
我怎么能写条件1以下?
我正在使用java中的DOM表示法如何知道标签是否包含值或其他标签?
如何区分xml标记是否具有值或具有其他嵌入标记? 例如,我可以有:
<item> 2 </item>
或
<item> <name> item1 </name> </item>
我想要做的
if(condition1 : there is no tags inside item tag) do ...
else do ...
我怎么能写条件1以下?
你能够通过遍历子节点列表测试每个孩子:
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
执行测试。但是,如果是子元素,则此方法将遍历您正在测试的整个片段,并分配大量内存。
ElementNodes有一个getElementsByTagName method。使用字符串'*'
作为参数来调用它(匹配所有标签名称),然后计算结果的数量。大于零并且有子元素。
如果在大文档的根目录上调用,这将需要很长时间并分配大量内存。 – phihag
NodeList nl = docEle.getElementsByTagName("item");
nl.getChildNodes();
可以遍历的childNodes得到节点类型,如果节点类型是文本,你可以把你的病情。
[childElementCount](http://www.w3.org/TR/ElementTraversal/#attribute-childElementCount):'x.childElementCount'(其中'x'是对元素的引用)。如果它返回零,则该元素没有子元素。 –
@ŠimeVidas这还没有成为DOM API的Java实现,有吗? – phihag
@phihag我不知道。 –