2012-07-30 46 views
0

我創建了一個xml文件並存儲在我的sdcard中。我使用DOM解析器來檢索它。我的xml文件就像。我使用了一個簡單的xml文件進行演示。是:如何在Android中使用DOM檢索xml元素

<?xml version="1.0"?> 
<root> 
    <staff> 
     <word>1</word> 
     <meaning>one</meaning> 

    </staff> 
    <staff> 
     <word>2</word> 
     <meaning>two</meaning> 

    </staff> 
</root> 

在我的活動我有的字給它應該顯示值在其meaning.Is給它可能做到這一點「一」的autocompletetextview.In它,當我進入1和怎麼樣?通過使用getElementsByTagName("staff")

得到的子節點getChildNodes()

+0

參見[這]( http://www.ibm.com/developerworks/opensource/library/x-android/) – 2012-07-30 12:59:15

+0

對我們來說更明智e SAX解析器或XmlPullParser,因爲您不會根據我的理解修改此xml文件。這些解決方案更高效。 – overbet13 2012-07-30 13:03:10

回答

0

獲取節點列表現在得到節點名getNodeName()和節點值getNodeValue()

看到這個下面的代碼:

Element root=doc.getDocumentElement();  
       NodeList nodeList=root.getElementsByTagName("staff"); 
       for(int i=0;i<nodeList.getLength();i++) 
       { 
        Node statenode=nodeList.item(i); 

        NodeList idList= statenode.getChildNodes(); 
        for(int j=0;j<idList.getLength();j++) 
        { 
         Node property = idList.item(j); 
        String name = property.getNodeName(); 


        if (name.equalsIgnoreCase("word")) 
        { 
        //Read your values here 

         Log.e("",property.getFirstChild().getNodeValue()); 

        } 
        if (name.equalsIgnoreCase("meaning")) 
        { 
         //Read your values here 
         Log.e("",property.getFirstChild().getNodeValue()); 

        } 
        } 

        }