2012-07-30 47 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()); 

        } 
        } 

        }