0

目前我正在使用 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>

如何解析这种格式?

4

3 回答 3

1

像这样定义一个新的解析器类,并在需要 XML 解析的地方实现这个类 public class 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中获取帮助

于 2013-03-19T05:32:26.603 回答
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.for xml 解析更多检查这个链接

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

于 2013-03-26T11:28:15.077 回答
0

解析 XML 内容并获取 Dom Element。

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;
    }
于 2013-03-19T04:30:37.797 回答