Android:如何在特定的xml标记下获取值

时间:2011-05-17 06:08:58

标签: android xml parsing url

我想在我的xml文件的特定标签下获取值(通过url访问),如下所示:

<SyncLoginResponse>
    <Videos>
    <Video>
        <name>27/flv</name>
        <title>scooter</title>
        <url>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/videos/</url>
        <thumbnail>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/thumbnails/106/jpg</thumbnail>

    </Video>
    <Video>
        <name>26/flv</name>
        <title>barsNtone</title>
        <url>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/videos/</url>
        <thumbnail>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/thumbnails/104/jpg</thumbnail>
    </Video>

    </Videos>
    <Slideshows>
    <Slideshow>
        <name>44</name>
        <title>ProcessFlow</title>
        <pages>4</pages>
        <url>http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/slideshows/</url>

    </Slideshow>
    </Slideshows>
<SyncLoginResponse>

如您所见,视频下方有“名称”标签,幻灯片下还有“名称”标签以及“标题”和“网址”。我想在幻灯片标签下获取值。

到目前为止,我有以下代码:

EngagiaSync.java:

package com.example.engagiasync;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;
public class EngagiaSync extends Activity {

    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
    private ProgressDialog mProgressDialog;
    public String FileName = "";
    public String FileURL = "";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
         super.onCreate(icicle);

         /* Create a new TextView to display the parsingresult later. */
         TextView tv = new TextView(this);
         tv.setText("...PARSE AND DOWNLOAD...");


         try {
              /* Create a URL we want to load some xml-data from. */
              URL url = new URL("http://somedomain.com/tabletcms/tablets/sync_login/jayem30/jayem");
              url.openConnection();
              /* Get a SAXParser from the SAXPArserFactory. */
              SAXParserFactory spf = SAXParserFactory.newInstance();
              SAXParser sp = spf.newSAXParser();

              /* Get the XMLReader of the SAXParser we created. */
              XMLReader xr = sp.getXMLReader();
              /* Create a new ContentHandler and apply it to the XML-Reader*/
              ExampleHandler myExampleHandler = new ExampleHandler();
              xr.setContentHandler(myExampleHandler);

              /* Parse the xml-data from our URL. */
              xr.parse(new InputSource(url.openStream()));
              /* Parsing has finished. */

              /* Our ExampleHandler now provides the parsed data to us. */
              List<ParsedExampleDataSet> parsedExampleDataSet = myExampleHandler.getParsedData();

              /* Set the result to be displayed in our GUI. */
              //tv.setText(parsedExampleDataSet.toString());
              String currentFile;
              String currentFileURL;
              int x = 1;
              Iterator i;
              i = parsedExampleDataSet.iterator();
              ParsedExampleDataSet dataItem;
              while(i.hasNext()){

                   dataItem = (ParsedExampleDataSet) i.next();

                   tv.append("\nName:> " + dataItem.getName());
                   tv.append("\nTitle:> " + dataItem.getTitle());
                   tv.append("\nPages:> " + dataItem.getPages());
                   tv.append("\nFile:> " + dataItem.getUrl());

                   /*
                   int NumPages = Integer.parseInt(dataItem.getPages());

                   while( x <= NumPages ){
                       currentFile = dataItem.getName() + "-" + x + ".jpg";
                       currentFileURL = dataItem.getUrl() + currentFile;

                       tv.append("\nName: " + dataItem.getName());
                       tv.append("\nTitle: " + dataItem.getTitle());
                       tv.append("\nPages: " + NumPages );
                       tv.append("\nFile: " + currentFile);

                       startDownload(currentFile, currentFileURL);
                       x++;
                   }
                   */

              }

         } catch (Exception e) {
              /* Display any Error to the GUI. */
              tv.setText("Error: " + e.getMessage());

         }
         /* Display the TextView. */
         this.setContentView(tv);
    }

    private void startDownload(String currentFile, String currentFileURL ){
        new DownloadFileAsync().execute(currentFile, currentFileURL);
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_DOWNLOAD_PROGRESS:
                mProgressDialog = new ProgressDialog(this);
                mProgressDialog.setMessage("Downloading files...");
                mProgressDialog.setIndeterminate(false);
                mProgressDialog.setMax(100);
                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mProgressDialog.setCancelable(true);
                mProgressDialog.show();
                return mProgressDialog;
            default:
                return null;
        }
    }


    class DownloadFileAsync extends AsyncTask<String, String, String>{

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(DIALOG_DOWNLOAD_PROGRESS);
        }


        @Override
        protected String doInBackground(String... strings) {

            try {
                String currentFile = strings[0];
                String currentFileURL = strings[1];

                File root = Environment.getExternalStorageDirectory();
                URL u = new URL(currentFileURL);
                HttpURLConnection c = (HttpURLConnection) u.openConnection();
                c.setRequestMethod("GET");
                c.setDoOutput(true);
                c.connect();

                int lenghtOfFile = c.getContentLength();

                FileOutputStream f = new FileOutputStream(new File(root + "/download/", currentFile));

                InputStream in = c.getInputStream();

                byte[] buffer = new byte[1024];
                int len1 = 0;
                long total = 0;

                while ((len1 = in.read(buffer)) > 0) {
                    total += len1; //total = total + len1
                    publishProgress("" + (int)((total*100)/lenghtOfFile));
                    f.write(buffer, 0, len1);
                }
                f.close();
            } catch (Exception e) {
                Log.d("Downloader", e.getMessage());
            }

            return null;

        }


        protected void onProgressUpdate(String... progress) {
            Log.d("ANDRO_ASYNC",progress[0]);
            mProgressDialog.setProgress(Integer.parseInt(progress[0]));
       }

       @Override
       protected void onPostExecute(String unused) {
           dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
       }


    }

}

ExampleHandler.java:

package com.example.engagiasync;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ExampleHandler extends DefaultHandler{

     // ===========================================================
     // Fields
     // ===========================================================

     private StringBuilder mStringBuilder = new StringBuilder();

     private ParsedExampleDataSet mParsedExampleDataSet = new ParsedExampleDataSet();
     private List<ParsedExampleDataSet> mParsedDataSetList = new ArrayList<ParsedExampleDataSet>();

     // ===========================================================
     // Getter & Setter
     // ===========================================================

     public List<ParsedExampleDataSet> getParsedData() {
          return this.mParsedDataSetList;
     }

     // ===========================================================
     // Methods
     // ===========================================================

     /** Gets be called on opening tags like:
      * <tag>
      * Can provide attribute(s), when xml was like:
      * <tag attribute="attributeValue">*/
     @Override
     public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
        if (localName.equals("Slideshow")) {
            this.mParsedExampleDataSet = new ParsedExampleDataSet();
        }

     }

     /** Gets be called on closing tags like:
      * </tag> */
     @Override
     public void endElement(String namespaceURI, String localName, String qName)
               throws SAXException {
          if (localName.equals("Slideshow")) {
               this.mParsedDataSetList.add(mParsedExampleDataSet);
          }else if (localName.equals("name")) {
               mParsedExampleDataSet.setName(mStringBuilder.toString().trim());
          }else if (localName.equals("title"))  {
              mParsedExampleDataSet.setTitle(mStringBuilder.toString().trim());
          }else if(localName.equals("pages"))  {
              mParsedExampleDataSet.setPages(mStringBuilder.toString().trim());
          }else if(localName.equals("url")){
              mParsedExampleDataSet.setUrl(mStringBuilder.toString().trim());
          }
          mStringBuilder.setLength(0);
     }

     /** Gets be called on the following structure:
      * <tag>characters</tag> */
     @Override
    public void characters(char ch[], int start, int length) {
          mStringBuilder.append(ch, start, length);
    }
}

ParsedExampleDataSet.java:

package com.example.engagiasync;

public class ParsedExampleDataSet {
    private String name = null;
    private String title = null;
    private String pages = null;
    private String url = null;


    //name
    public String getName() {
         return name;
    }
    public void setName(String name) {
         this.name = name;
    }

    //title
    public String getTitle(){
        return title;
    }
    public void setTitle(String title){
        this.title = title;
    }

    //pages
    public String getPages(){
        return pages;
    }
    public void setPages(String pages){
        this.pages = pages;
    }

    //url
    public String getUrl(){
        return url;
    }
    public void setUrl(String url){
        this.url = url;
    }

    /*
    public String toString(){
         return "Firstname: " + this.firstname + "\n" + "Lastname: " + this.lastname + "\n" + "Address: " + this.Address + "\nFile URL: " + this.FileURL + "\n\n";
    }
    */

}

以上代码在UI中返回以下结果:

...PARSE AND DOWNLOAD...
Name:> 27/flv
Title:> scooter
Pages:> 4
File:> http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/videos/

我希望它是:

...PARSE AND DOWNLOAD...
Name:> 44
Title:> ProcessFlow
Pages:> 4
File:> http://dev2.somedomain.com/tabletcms/tablets/tablet_content/000002/slideshows/

3 个答案:

答案 0 :(得分:2)

尝试使用DOM解析器而不是SAX解析器....

input=httpconnection.openHttpConnection(url);
            isr = new InputStreamReader(input);
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilder = documentBuilderFactory.newDocumentBuilder();
            document = documentBuilder.parse(input, null);
            document.getDocumentElement().normalize();
            NodeList videosList = document.getElementsByTagName("Video");
            for (int i = 0; i < videosList .getLength(); i++) 
            {
                         Node node = videosList .item(i);
                Element playlistElement = (Element) node;
                NodeList title = playlistElement.getElementsByTagName("name");
                if (title.item(0).getChildNodes().item(0) != null) 
                {   
                    Element nameElement = (Element) title.item(0);
                    title = nameElement.getChildNodes();
                    Log.v("name===>",((Node) title.item(0)).getNodeValue());
                }

//Like wise use the same code for title ,url ,thumbnail...
            }

答案 1 :(得分:1)

HI,

保留父标记的布尔变量

并在EndElement()方法中检查父标记是否为真;

如果为true,则将该特定值存储到相应的变量中。

e.g。

如果你有

<ResultSet>
<result>
<name>a</name>
</result>
<customresult>
<name>avs</customresult>
</ResultSet>

取两个变量作为结果&amp;自定义布尔类型;

最初将它们标记为false,

检查startElement()方法是否解析是否以Result元素开始,如果是的话

然后将其标记为真实。

&安培;现在你知道你正在解析结果,所以你可以很容易地识别

中的变量

结果。

最诚挚的问候,

~Anup

答案 2 :(得分:1)

public class XMLHandler extends DefaultHandler 
{
    boolean result;
boolean customresult;
    String temp;

    @Override
    public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException 
    {


        else if (localName.equalsIgnoreCase("result"))
        {
            result = true;
        }
        else if(localName.equalsIgnoreCase("customresult"))
        {
            customresult =true;
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName)throws SAXException {

        /** set value */ 
        if (localName.equalsIgnoreCase("name") && result == true)
        {
                  String name = temp; //which is nothing but your name from result tag

        }
        else if(localName.equalsIgnoreCase("name") && result == true)
        {
            String name = temp; //which is nothing but your name from customresult tag
        }
            else if(localName.equalsIgnoreCase("result"))
        {
                 result = false;
        }
            else if(localName.equalsIgnoreCase("customresult"))
        {
                 customresult = false;
        }
    }

    /** Called to get tag characters ( ex:- <name>AndroidPeople</name> 
     * -- to get AndroidPeople Character ) */
    @Override
    public void characters(char[] ch, int start, int length)throws SAXException
    {
        temp = new String(ch, start, length);
    }


}

这就是我的朋友如果你发现它很有用,那就别忘了把它标记为答案。