我有这样的 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。
由于 Cars 有 2 个第一个子节点,我怎样才能得到这个长度,即 2?
最佳答案
这只能通过自己的代码或 XPath 进行。
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("/Cars/Car");
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
关于Java DOM : Number of first child nodes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9923216/