Muhammad Imran Tariq
Muhammad Imran Tariq

Reputation: 23352

Java DOM: Number of first child nodes

I have XML like this

<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(); gives length of all descendant nodes. So in this case it gives 5. As there are 2 first child nodes of Cars, how can I get that length i.e. 2?

Upvotes: 1

Views: 376

Answers (1)

Joop Eggen
Joop Eggen

Reputation: 109597

That only goes by own code or XPath.

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

Upvotes: 2

Related Questions