2011-05-17 68 views
2

我想在我的xml文件的特定標籤值的值(通過URL訪問),它看起來像這樣:Android的:如何獲得在特定的XML標記

<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/ 
+0

不要使用DOM解析器和SAX解析器,它們都會讓生活變得比需要的難得多。只需使用Simple XML框架即可。我非常喜歡它,我寫了一篇博客文章:http://robertmassaioli.wordpress.com/2011/04/21/simple-xml-in-android-1-5-and-up/ – 2011-05-17 11:10:00

回答

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); 
    } 


} 

這就是我所有的朋友如果你覺得有用,然後不要忘記將其標記爲一個答案。

+0

非常感謝你我的朋友!你救了我的一天! :) – Kris 2011-05-18 10:03:36

+0

你最歡迎... – 2011-05-18 12:22:49

1

HI,

保持爲布爾變量父母標籤,

並在EndElem ent()方法,父標籤是否爲真;

如果它是真的,則將該特定值存儲到相應的變量即全部。

例如

,如果你有

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

採取兩個變量作爲結果& customresult布爾類型;

它們標記爲錯誤的開始,

檢查中的startElement()方法是否解析開始與結果元素,如果它這樣

然後將其標記爲真。

&現在你知道你正在分析的結果,所以你可以很容易地識別在

結果的變量。

最好的問候,

〜阿努普

+0

對不起noob問題,但是,你有一個關於如何在我的情況下設置這些布爾變量的示例代碼?無論如何,謝謝你的迴應! :) – Kris 2011-05-17 06:47:36

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... 
      }