2012-03-29 71 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); 
相關問題