如何使用dom解析器从xml解析中获取数据?

时间:2014-07-21 12:22:44

标签: android xml parsing

我是xml解析的新手。在我的xml解析数据中有这样的

<popularmakes>
   <make>
    <name>Maruti Suzuki</name>
      <brandlogo>
        <ldpi><![CDATA[http://www.cartrade.com/images/logos/png/68/Maruti-Suzuki.png]]></ldpi>
        <mdpi><![CDATA[http://www.cartrade.com/images/logos/png/90/Maruti-Suzuki.png]]></mdpi>
     </brandlogo>
   </make>

   <name>Maruti Suzuki</name>
      <brandlogo>
        <ldpi><![CDATA[http://www.cartrade.com/images/logos/png/68/Maruti-Suzuki.png]]></ldpi>
        <mdpi><![CDATA[http://www.cartrade.com/images/logos/png/90/Maruti-Suzuki.png]]></mdpi>
     </brandlogo>
   </make>
   .......
   .......
   .......
   <name>Maruti Suzuki</name>
      <brandlogo>
        <ldpi><![CDATA[http://www.cartrade.com/images/logos/png/68/Maruti-Suzuki.png]]></ldpi>
        <mdpi><![CDATA[http://www.cartrade.com/images/logos/png/90/Maruti-Suzuki.png]]></mdpi>
     </brandlogo>
   </make>      
 </popularmakes>

 <othermakes>
   <make>
    <name>Maruti Suzuki</name>
      <brandlogo>
        <ldpi><![CDATA[http://www.cartrade.com/images/logos/png/68/Maruti-Suzuki.png]]></ldpi>
        <mdpi><![CDATA[http://www.cartrade.com/images/logos/png/90/Maruti-Suzuki.png]]></mdpi>
     </brandlogo>
   </make>

   <name>Maruti Suzuki</name>
      <brandlogo>
        <ldpi><![CDATA[http://www.cartrade.com/images/logos/png/68/Maruti-Suzuki.png]]></ldpi>
        <mdpi><![CDATA[http://www.cartrade.com/images/logos/png/90/Maruti-Suzuki.png]]></mdpi>
     </brandlogo>
   </make>
   .......
   .......
   .......
   <name>Maruti Suzuki</name>
      <brandlogo>
        <ldpi><![CDATA[http://www.cartrade.com/images/logos/png/68/Maruti-Suzuki.png]]></ldpi>
        <mdpi><![CDATA[http://www.cartrade.com/images/logos/png/90/Maruti-Suzuki.png]]></mdpi>
     </brandlogo>
   </make>      
 </othermakes>

在这里我使用dom解析器来获取数据。但我无法做到这一点。我在谷歌很多但是所有样本只有一个节点数据。在这个xml解析如何得到 name < / strong>和 brandlogo即图片ldpi和mdpi 。特别是如何获取数据,即branddo.my问题中的ldpi和mdpi是在ldpi内部,mdpi CDATA 可用。所以我无法解析数据。所以请建议我怎么做。谢谢所有人..

2 个答案:

答案 0 :(得分:0)

android DOM Xml解析的示例 activity_main.xml中

从托盘中拖出一个textview。现在activity_main.xml文件将如下所示: 文件:activity_main.xml

<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    tools:context=".MainActivity" >  

    <TextView  
        android:id="@+id/textView1"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignParentLeft="true"  
        android:layout_alignParentTop="true"  
        android:layout_marginLeft="75dp"  
        android:layout_marginTop="46dp"  
        android:text="TextView" />  

</RelativeLayout>  

xml文档

在项目的assets目录中创建名为file.xml的xml文件。 文件:file.xml

<?xml version="1.0"?>  
<records>  
<employee>  
<name>Sachin Kumar</name>  
<salary>50000</salary>  
</employee>  
<employee>  
<name>Rahul Kumar</name>  
<salary>60000</salary>  
</employee>  
<employee>  
<name>John Mike</name>  
<salary>70000</salary>  
</employee>  
</records>  

活动类

让我们编写代码来使用dom解析器解析xml。 文件:MainActivity.java

import java.io.InputStream;  

import javax.xml.parsers.DocumentBuilder;  
import javax.xml.parsers.DocumentBuilderFactory;  
import org.w3c.dom.Document;  
import org.w3c.dom.Element;  
import org.w3c.dom.Node;  
import org.w3c.dom.NodeList;  
import android.app.Activity;  
import android.os.Bundle;  
import android.widget.TextView;  

public class MainActivity extends Activity {  
TextView tv1;  

@Override  
public void onCreate(Bundle savedInstanceState) {  
super.onCreate(savedInstanceState);  
setContentView(R.layout.activity_main);  
tv1=(TextView)findViewById(R.id.textView1);  
try {  
InputStream is = getAssets().open("file.xml");  

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();  
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();  
Document doc = dBuilder.parse(is);  

Element element=doc.getDocumentElement();  
element.normalize();  

NodeList nList = doc.getElementsByTagName("employee");  
for (int i=0; i<nList.getLength(); i++) {  

Node node = nList.item(i);  
if (node.getNodeType() == Node.ELEMENT_NODE) {  
Element element2 = (Element) node;  
tv1.setText(tv1.getText()+"\nName : " + getValue("name", element2)+"\n");  
tv1.setText(tv1.getText()+"Salary : " + getValue("salary", element2)+"\n");  
tv1.setText(tv1.getText()+"-----------------------");  
}  
}//end of for loop  

} catch (Exception e) {e.printStackTrace();}  

}  
private static String getValue(String tag, Element element) {  
NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();  
Node node = (Node) nodeList.item(0);  
return node.getNodeValue();  
}  

}  

答案 1 :(得分:0)

创建一个名为XmlParser的类

public class XMLParser {
// constructor
        public XMLParser() {

        }

        /**
         * Getting XML from URL making HTTP request
         * @param url string
         * */
        public String getXmlFromUrl(String url) {
            String xml = null;

            try {
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                xml = EntityUtils.toString(httpEntity);

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // return XML
            return xml;
        }

        /**
         * Getting XML DOM element
         * @param XML string
         * */
        public Document getDomElement(String xml){
            Document doc = null;
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            try {

                DocumentBuilder db = dbf.newDocumentBuilder();

                InputSource is = new InputSource();
                    is.setCharacterStream(new StringReader(xml));
                    doc = db.parse(is); 

                } catch (ParserConfigurationException e) {
                    Log.e("Error: ", e.getMessage());
                    return null;
                } catch (SAXException e) {
                    Log.e("Error: ", e.getMessage());
                    return null;
                } catch (IOException e) {
                    Log.e("Error: ", e.getMessage());
                    return null;
                }

                return doc;
        }

        /** Getting node value
          * @param elem element
          */
         public final String getElementValue( Node elem ) {
             Node child;
             if( elem != null){
                 if (elem.hasChildNodes()){
                     for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
                         if( child.getNodeType() == Node.TEXT_NODE  ){
                             return child.getNodeValue();
                         }
                     }
                 }
             }
             return "";
         }

         /**
          * Getting node value
          * @param Element node
          * @param key string
          * */
         public String getValue(Element item, String str) {     
                NodeList n = item.getElementsByTagName(str);        
                return this.getElementValue(n.item(0));
            }




}

在asyncTask的doinBg方法中创建此代码:

ArrayList<HashMap<String, String>> urList = new ArrayList<HashMap<String, String>>();

    XMLParser parser = new XMLParser();
    String xml = parser.getXmlFromUrl(URL); // getting XML from URL
    Document doc = parser.getDomElement(xml); // getting DOM element

    NodeList nl = doc.getElementsByTagName("make");
    // looping through all song nodes <song>
    for (int i = 0; i < nl.getLength(); i++) {
        // creating new HashMap
        HashMap<String, String> map = new HashMap<String, String>();
        Element e = (Element) nl.item(i);
        // adding each child node to HashMap key => value
        map.put("name", parser.getValue(e, "name"));
        map.put("ldpi", parser.getValue(e, "ldpi"));
        map.put("mdpi", parser.getValue(e, "mdpi"));


        // adding HashList to ArrayList
        urList .add(map);
    }

希望你知道如何使用那个arraylist now..happy编码 如果有任何疑问,请告诉我。