Java DOM:第一个子节点的数量

时间:2012-03-29 10:06:33

标签: java xml dom

我有这样的XML

<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?

1 个答案:

答案 0 :(得分:2)

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

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