2011-06-17 79 views
5

我有一個這樣的XML:從Android(XML)文檔中的節點通過標記名獲取元素?

<!--...--> 
    <Cell X="4" Y="2" CellType="Magnet"> 
    <Direction>180</Direction> 
    <SwitchOn>true</SwitchOn> 
    <Color>-65536</Color> 
    </Cell> 
    <!--...--> 

有許多是Cell elements,我可以通過GetElementsByTagName得到小區節點。但是,我意識到Node類沒有GetElementsByTagName方法!我怎樣才能從該單元節點獲得Direction節點,而不需要經過ChildNodes的列表?我可以通過標記名稱從Document類中獲得NodeList嗎?

謝謝。

回答

13

您可以用Element再次投下NodeList項目,然後從Element類別中使用getElementsByTagName();。 最好的方法是在您的項目中製作Cell Object以及Direction,Switch,Color等字段。然後讓你的數據像這樣。

String direction []; 
NodeList cell = document.getElementsByTagName("Cell"); 
int length = cell.getLength(); 
direction = new String [length]; 
for (int i = 0; i < length; i++) 
{ 
    Element element = (Element) cell.item(i); 
    NodeList direction = element.getElementsByTagName("Direction"); 

    Element line = (Element) direction.item(0); 

    direction [i] = getCharacterDataFromElement(line); 

    // remaining elements e.g Switch , Color if needed 
} 

其中你的getCharacterDataFromElement()將如下。

public static String getCharacterDataFromElement(Element e) 
{ 
    Node child = e.getFirstChild(); 
    if (child instanceof CharacterData) 
    { 
     CharacterData cd = (CharacterData) child; 
     return cd.getData(); 
    } 
    return ""; 
} 
+0

謝謝,我忘了Node可以投到Element!快樂編碼:) – 2011-06-17 06:29:30

相關問題