在 Android 上解析 XML [英] Parse XML on Android

查看:20
本文介绍了在 Android 上解析 XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Android 应用程序中为我们的计费系统使用 API,但我无法弄清楚如何解析它返回的 XML.到目前为止,这是我的函数的样子......

I am trying to use the API for our billing system in an Android Application, but I am having trouble figuring out how to parse the XML that it returns. Here is what my function looks like thus far...

public void ParseData(String xmlData)
{
    try
    {
        // Document Builder
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = factory.newDocumentBuilder();

        // Input Stream
        InputSource inStream = new InputSource();
        inStream.setCharacterStream(new StringReader(xmlData));

        // Parse Document into a NodeList
        Document doc = db.parse(inStream);
        NodeList nodes = doc.getElementsByTagName("ticket");

        // Loop NodeList and Retrieve Element Data
        for(int i = 0; i < nodes.getLength(); i++)
        {
            Node node = nodes.item(i);

            if (node instanceof Element)
            {
                Element child = (Element)node;
                String id = child.getAttribute("id");
            }
        }
    }
    catch(SAXException e)
    {

    }
}

这是返回的 XML 数据的样子.我需要遍历每个元素并拉出每个元素,但我不知道如何使用 DOM 解析器来做到这一点.

and here is what the XML data looks like that is returned. I need to loop through each and pull each element out, but I cant figure out how to do that with the DOM parser.

<whmcsapi> 
 <action>gettickets</action> 
 <result>success</result> 
 <totalresults>1</totalresults> 
 <startnumber>0</startnumber> 
 <numreturned>1</numreturned> 
 <tickets> 
  <ticket> 
   <id>1</id> 
   <tid>557168</tid> 
   <deptid>1</deptid> 
   <userid>1</userid> 
   <name><![CDATA[Array]]></name> 
   <email></email> 
   <cc></cc> 
   <c>TmDEga5v</c> 
   <date>2009-08-03 23:14:32</date> 
   <subject><![CDATA[Test Ticket]]></subject> 
   <message><![CDATA[This is a test ticket> 

   ---------------------------- 
   IP Address: xxx.xxx.xxx.xxx]]></message> 
   <status>Open</status> 
   <priority>Medium</priority> 
   <admin></admin> 
   <attachment></attachment> 
   <lastreply>2009-08-04 12:14:18</lastreply> 
   <flag>0</flag> 
   <service></service> 
  </ticket> 
 </tickets> 
</whmcsapi>

推荐答案

  1. 在库文件夹中添加java-json.jar
  2. 编译文件 ('libs/java-json.jar')//将此行添加到您的构建中
  1. Add java-json.jar in library folder
  2. Compile files ('libs/java-json.jar') //add this line into your build

这里是将 xml 响应转换为 json 响应的代码:

Here is the code to convert xml response to json response:

JSONObject jsonObj = null;
try {
        jsonObj = XML.toJSONObject(response.toString());
} catch (JSONException e) {
        Log.e("JSON exception", e.getMessage());
        e.printStackTrace();
}

这篇关于在 Android 上解析 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆