2011-04-22 194 views
6

我有一個自定義的contentHandler(稱爲XMLHandler),我去過很多通過Google和StackOverflow的網站,詳細介紹如何設置它。Android:從字符串問題解析XML

我不明白的是如何使用它。

Xml.parse(...,...)不返回任何內容,因爲它是一個無效方法。

如何訪問我已解析的XML數據?

我意識到這個問題可能是微不足道的,但我一直在尋找(字面上)小時,並沒有找到解決辦法。

請幫助。

String result = fetchData(doesntmatter); 
Xml.parse(result, new XMLHandler()); 
+0

你能發佈你的XMLhandler嗎? – 2011-04-22 05:43:49

回答

12

下面是一個例子,我希望這將是有益的理解「的SAXParser」

package test.example; 

import java.io.BufferedReader; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.net.URL; 

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

import org.xml.sax.InputSource; 
import org.xml.sax.SAXException; 
import org.xml.sax.XMLReader; 
import org.xml.sax.helpers.DefaultHandler; 

import android.app.Activity; 
import android.os.Bundle; 
import android.util.Log; 
import android.widget.TextView; 

public class XMLParsingDemo extends Activity { 

    private final String MY_DEBUG_TAG = "WeatherForcaster"; 

    /** 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); 

     try { 
      /* Create a URL we want to load some xml-data from. */ 

     DefaultHttpClient hc = new DefaultHttpClient(); 
     ResponseHandler <String> res = new BasicResponseHandler(); 
     HttpPost postMethod = new HttpPost("http://www.anddev.org/images/tut/basic/parsingxml/example.xml"); 
     String response=hc.execute(postMethod,res); 

     /* 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. */ 
     InputSource inputSource = new InputSource(); 
     inputSource.setEncoding("UTF-8"); 
     inputSource.setCharacterStream(new StringReader(response)); 

     /* Parse the xml-data from our URL. */ 
     xr.parse(inputSource); 
     /* Parsing has finished. */ 

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


     /* Set the result to be displayed in our GUI. */ 
     tv.setText(response + "\n\n\n***************************************" + parsedExampleDataSet.toString()); 



     } catch (Exception e) { 
      /* Display any Error to the GUI. */ 
      tv.setText("Error: " + e.getMessage()); 
      Log.e(MY_DEBUG_TAG, "WeatherQueryError", e); 
     } 
     /* Display the TextView. */ 
     this.setContentView(tv); 
    } 

    public class ExampleHandler extends DefaultHandler { 

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

     private boolean in_outertag = false; 
     private boolean in_innertag = false; 
     private boolean in_mytag = false; 

     private ParsedExampleDataSet myParsedExampleDataSet = new ParsedExampleDataSet(); 

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

     public ParsedExampleDataSet getParsedData() { 
      return this.myParsedExampleDataSet; 
     } 

     // =========================================================== 
     // Methods 
     // =========================================================== 
     @Override 
     public void startDocument() throws SAXException { 
      this.myParsedExampleDataSet = new ParsedExampleDataSet(); 
     } 

     @Override 
     public void endDocument() throws SAXException { 
      // Nothing to do 
     } 

     /** Gets be called on opening tags like: 
     * <tag> 
     * Can provide attribute(s), when xml was like: 
     * <tag attribute="attributeValue">*/ 
     @Override 
     public void startElement(String uri, String localName, String qName, org.xml.sax.Attributes atts) throws SAXException { 
      super.startElement(uri, localName, qName, atts); 
      if (localName.equals("outertag")) { 
       this.in_outertag = true; 
      } 
      else if (localName.equals("innertag")) { 
       String attrValue = atts.getValue("sampleattribute"); 
       myParsedExampleDataSet.setExtractedString(attrValue); 
       this.in_innertag = true; 
      } 
      else if (localName.equals("mytag")) { 
       this.in_mytag = true; 
      } 
      else if (localName.equals("tagwithnumber")) { 
       // Extract an Attribute 
       String attrValue = atts.getValue("thenumber"); 
       int i = Integer.parseInt(attrValue); 
       myParsedExampleDataSet.setExtractedInt(i); 
      } 

     } 


     /** Gets be called on closing tags like: 
     * </tag> */ 
     @Override 
     public void endElement(String namespaceURI, String localName, String qName) 
       throws SAXException { 
      if (localName.equals("outertag")) { 
       this.in_outertag = false; 
      }else if (localName.equals("innertag")) { 
       this.in_innertag = false; 
      }else if (localName.equals("mytag")) { 
       this.in_mytag = false; 
      }else if (localName.equals("tagwithnumber")) { 
       // Nothing to do here 
      } 
     }  


     /** Gets be called on the following structure: 
     * <tag>characters</tag> */ 
     @Override 
     public void characters(char ch[], int start, int length) { 
      if(this.in_mytag){ 
       myParsedExampleDataSet.setExtractedString(new String(ch)); 
      } 
     } 
    } 

    public class ParsedExampleDataSet { 
     private String extractedString = null; 
     private int extractedInt = 0; 

     public String getExtractedString() { 
      return extractedString; 
     } 
     public void setExtractedString(String extractedString) { 
      this.extractedString = extractedString; 
     } 

     public int getExtractedInt() { 
      return extractedInt; 
     } 
     public void setExtractedInt(int extractedInt) { 
      this.extractedInt = extractedInt; 
     } 

     public String toString(){ 
      return "\n\n\nExtractedString = " + this.extractedString 
        + "\n\n\nExtractedInt = " + this.extractedInt; 
     } 

    } 

} 
+1

謝謝,這正是我所需要的。 – Donut 2011-04-23 00:44:16

1

您有權訪問你的XML數據轉換,你必須通過XMLHandler()

定義處理程序

你必須覆蓋

public void startElement(String uri, String localName, String qName, org.xml.sax.Attributes atts) throws SAXException { 

} 


@Override 
    public void endElement(String namespaceURI, String localName, String qName) { 

} 

@Override 
    public void characters(char ch[], int start, int length) { 

    } 
+0

我已經有一個處理程序,並且我在該問題中指定了該處理程序。我的問題是我如何使用它。 Vaibhav Jani用一個例子回答了這個問題。 – Donut 2011-04-23 00:43:56

+0

如果我的字符串包含輸入或某些特殊字符? – MobileEvangelist 2012-10-05 08:29:26

+0

創建一個字符串緩衝區並將字符串追加到緩衝區中,直到標籤結束。 – Dharmendra 2012-10-05 08:55:46