2012-03-29 40 views
1

我有这样的XMLJava的DOM:第一个孩子的节点数目

<Cars> 
    <Car name="abc" title="car length" length="20" type="type1" /> 
    <Car name="abc" title="car length" length="20" type="type2"> 
     <Car name="abc" title="car length" length="20" type="type1" /> 
     <Car name="abc" title="car length" length="20" type="type1" /> 
     <Car name="abc" title="car length" length="20" type="type1" /> 
    </Car> 
</Cars> 

Element carNode = ...; 
NodeList carList = carNode.getElementsByTagName("Car"); 
carList.getLength(); 

carList.getLength();给出了所有子节点的长度。所以在这种情况下,它给出了5. 由于有2个第一个子节点汽车,我怎么能得到那个长度,即2?

+0

为什么要这样?我认为这是不可能的getElementsByTagName()返回匹配的标记名,所以它会每次返回5个长度。 – 2012-03-29 10:40:26

+0

这是要求。 XML标签名称不能更改。有没有办法返回第一个孩子节点的长度?而不是后代的孩子。 – 2012-03-29 10:46:46

+0

你必须使用迭代器,我认为没有捷径! – 2012-03-29 10:54:54

回答

2

这只能通过自己的代码或XPath。

XPath xpath = XPathFactory.newInstance().newXPath(); 
XPathExpression expr = xpath.compile("/Cars/Car"); 
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); 
相关问题