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

查看:134
本文介绍了在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>


推荐答案

是SAX解析器是解决方案,这里是基本的代码让你开始:

Yes SAX parser is the solution and here is the basic code to get you started:

void parseExampleFunction(){
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp = spf.newSAXParser();
    XMLReader xr = sp.getXMLReader();

    File myFile = new File( //the XML file which you need to parse );
    myFile.createNewFile();

    FileInputStream fOut =  new FileInputStream(myFile);
    BufferedInputStream bos = new BufferedInputStream( fOut );

    /** Create handler to handle XML Tags ( extends DefaultHandler ) */

    MessagesXMLHandler myXMLHandler = new MessagesXMLHandler(context);
    xr.setContentHandler(myXMLHandler);
    xr.parse(new InputSource(bos));
}

// the class where the parsing logic needs to defined.This preferably can be in a different .java file 
public class MessagesXMLHandler extends DefaultHandler{

    //this function is called automatically when a start tag is encountered
    @Override
    public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException 
    //variable localName is the name of the tag

    //this function is called autiomatically when an end tag is encountered
    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
    }

    //this function gets called to return the value stored betweeen the closing and opening tags
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        //now variable value has the value stored between the closing and opening tags
        String value=new String(ch,start,length);
    }
}

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

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