Java DOM : Number of first child nodes

标签 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。 由于 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/

相关文章:

java - 在扫雷游戏中发现没有地雷的地区

java - 为什么这个java代码不能使用逃逸分析?

xml - 如何将多个 xml 文件转换并合并为一个文件

java - 我如何访问随机 string.xml

php - 防止 DOMDocument::loadHTML() 转换实体

java - 在 YAML 中表示常量的最佳方式是什么?

java - 扩展List增加字段是否合适

php - 如何在 Flex 中创建和访问带有属性的 xml

javascript - 我如何使用 jquery 获取表的 TD 中存在的值表?

javascript - 使用 javascript 创建下拉 <select><option> 元素