【问题标题】:How to achieve XML parsing in Android?如何在Android中实现XML解析?
【发布时间】:2013-03-19 04:26:39
【问题描述】:

目前我正在使用 Android 中的 XML 解析。我不知道它是如何工作的。我正在使用以下代码:

HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(MobileServiceConst.URL);
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("method", new StringBody(MobileServiceConst.UPLOAD_CONTACTS));
reqEntity.addPart("user_id", new StringBody(String.valueOf(Constants.userData.getUserInfo().getuserId())));
reqEntity.addPart("accesstoken", new StringBody(Constants.userData.getMYToken()));
reqEntity.addPart("data",new StringBody(jsnConts.toString()));
reqEntity.addPart("device_id",new StringBody(regId));
postRequest.setEntity(reqEntity);


HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));



StringBuilder s = new StringBuilder();

    while ((sResponse = reader.readLine()) != null) {

           s = s.append(sResponse);

    }

sResponse = s.toString();

System.out.println("responseeeeeeeeeeeeeee"+sResponse);

sResponse 采用以下格式:

<CS_Mservice_Main generator="check" version="1.0">
<getContacts>
<mycnt>
<key_0>
<id>1</id>
<user_id>22434</user_id>
<device_id>121212,</device_id>
<contact_id></contact_id>
<firstname></firstname>
<lastname></lastname>
<email></email>
<email1></email1>
<email2></email2>
<contact1>9809788201</contact1>
<contact2></contact2>
<contact3></contact3>
<contact4></contact4>
<created_at>2013-03-18 13:29:12</created_at>
</key_0>
<key_1>
<id>16</id>
<user_id>17025</user_id>
<device_id>APA91bGRyoeOlxZjhfjkdshjsdfsdsdf9kICZFsveU_QonqbNIbYONWLtiHpT4CmPe1aJg3rZ86noqj2HKshgZRlk1dc0Em7AVte2usHaP-qRzVBcP8BWzJuXa8ozA</device_id>
<contact_id></contact_id>
<firstname>Rahul</firstname>
<lastname>Jain</lastname>
<email>rahul.jain@abc.in</email>
<email1></email1>
<email2></email2>
<contact1></contact1>
<contact2></contact2>
<contact3></contact3>
<contact4></contact4>
<created_at>2013-03-18 13:30:04</created_at>
</key_1>
</mycnt>
<email/>
<sms/>
<status>success</status>
</getContacts>
</CS_Mservice_Main>

如何解析这种格式?

【问题讨论】:

标签: android xml-parsing


【解决方案1】:
import java.io.IOException;
 import java.io.StringReader;

 import org.xmlpull.v1.XmlPullParser;
 import org.xmlpull.v1.XmlPullParserException;
 import org.xmlpull.v1.XmlPullParserFactory;

 public class SimpleXmlPullApp
 {

     public static void main (String args[])
         throws XmlPullParserException, IOException
     {
         XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
         factory.setNamespaceAware(true);
         XmlPullParser xpp = factory.newPullParser();

         xpp.setInput( new StringReader ( "<foo>Hello World!</foo>" ) );
         int eventType = xpp.getEventType();
         while (eventType != XmlPullParser.END_DOCUMENT) {
          if(eventType == XmlPullParser.START_DOCUMENT) {
              System.out.println("Start document");
          } else if(eventType == XmlPullParser.START_TAG) {
              System.out.println("Start tag "+xpp.getName());
          } else if(eventType == XmlPullParser.END_TAG) {
              System.out.println("End tag "+xpp.getName());
          } else if(eventType == XmlPullParser.TEXT) {
              System.out.println("Text "+xpp.getText());
          }
          eventType = xpp.next();
         }
         System.out.println("End document");
     }
 }

试试这个在android中进行xml解析。更多检查这个链接

http://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html

【讨论】:

    【解决方案2】:

    像这样定义一个新的解析器类,并在需要 XML 解析的任何地方实现这个类 公共类 XMLParser {

    public String getXmlFromUrl(String url) {
        String xml = null;
    
        try {
            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;
    }
    
    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;
    }
    
    public String getValue(Element item, String str) {
        NodeList n = item.getElementsByTagName(str);
        return this.getElementValue(n.item(0));
    }
    
    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 "";
    } 
    
    }
    

    现在你需要调用这个解析类,它会接受 URL 作为输入并返回文档对象作为结果

    如果 XML 资源是静态的,则必须将 XMl 放在 Res 文件夹中,否则您可以遵循此结构

    像这样创建一个 XMLParser 类的对象

    parser = new XMLParser();
    xml = parser.getXmlFromUrl(URL);
    doc = parser.getDomElement(xml);
    

    比获取一个哈希图并存储各个标签的输出

    NodeList nl = doc.getElementsByTagName(KEY_ITEM);
            // looping through all item nodes <item>
            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(KEY_ID, "ID id:" +parser.getValue( e, KEY_ID));
                map.put(KEY_NAME, "Name" + parser.getValue( e, KEY_NAME));
                map.put(KEY_COST, "Rs." + parser.getValue( e, KEY_COST));
                map.put(KEY_DESC, "Desc:  "+ parser.getValue( e, KEY_DESC));
    
    
    
                // adding HashList to ArrayList
                menuItems.add(map);
    
            }
            getXML();
    

    您也可以从本教程中获得帮助Source

    【讨论】:

      【解决方案3】:

      解析 XML 内容并获取 Dom 元素。

      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 DOM
                  return doc;
          }
      

      【讨论】:

      • 03-19 10:16:18.425: I/System.out(10063): Docccccccccccccccccccccccccccccccorg.apache.harmony.xml.dom.DocumentImpl@42381c78,我得到了文档,然后下一步我要做什么想做什么?
      猜你喜欢
      • 2013-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-27
      • 2013-10-04
      • 2014-05-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多