2011-09-21 2 views
1

아래 XML 예제에서 SAX 구문 분석을 사용하여 XML 문서에서 데이터를 가져 오는 방법을 보여줄 수 있습니다.android에서 SAX 파싱을 사용하여 데이터를 가져 오는 방법

<root> 
    <parent> 
     <child1>xyz</child1> 
     <child2>abc</child2> 
    </parent> 
</root>   

어떻게하면 안드로이드에 색소 파싱 코드를 쓸 수 있습니까?

도와 주셔서 감사합니다 ...

답변

1

SAX 튜토리얼과 답변이 많이 있습니다. Here은 StackOverflow의 좋은 대답 중 하나입니다. SAX 파서가 어떻게 작동하는지에 대한 깨끗한 잣대를 설명합니다!

1
public class JaappApplication extends Application { 
     public static final int FAIL = 0; 
     public static final int SUCCESS = 1; 

     //XML parsers 
     public static final int QUESTIONS = 0; 


     //PUTEXTRAS 
     public static final String SUBJECTID = "subjectid"; 
     public static String subtypeid; 
     public static String subtypeoption; 

    } 

    public static ArrayList<QuestionsDto> getQuestionsDtos(String quesid) 
    { 
     ArrayList<QuestionsDto> arr = new ArrayList<QuestionsDto>(); 
     String url1 = url + "getquestions.php?subjectid=" + quesid; 
     XMLParser xmlParser = new XMLParser(JaappApplication.QUESTIONS); 
     int x = xmlParser.parseXml(url1, JaappApplication.QUESTIONS); 
     arr = xmlParser.getQuestions(); 
     return arr; 
    } 

       package com.jaapp.xmlparsing; 

     import java.io.InputStream; 
     import java.net.URI; 
     import java.net.UnknownHostException; 
     import java.util.ArrayList; 

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

     import org.apache.http.HttpResponse; 
     import org.apache.http.client.HttpClient; 
     import org.apache.http.client.methods.HttpGet; 
     import org.apache.http.impl.client.DefaultHttpClient; 
     import org.xml.sax.InputSource; 
     import org.xml.sax.XMLReader; 

     import com.jaapp.application.JaappApplication; 
     import com.jaapp.dto.QuestionsDto; 

     import android.util.Log; 

     public class XMLParser { 
      protected static final String TAG = XMLParser.class.getCanonicalName(); 
      private static QuestionsReader questionHandler; 

      public XMLParser(int initHandler) { 
       if (initHandler == JaappApplication.QUESTIONS) { 
        questionHandler = new QuestionsReader(); 
       } 
      } 

      public int parseXml(String parseString, int type) { 
       try { 
        /* Create a URL we want to load some xml-data from. */ 
        URI lUri = new URI(parseString); 

        // Prepares the request. 
        HttpClient lHttpClient = new DefaultHttpClient(); 
        HttpGet lHttpGet = new HttpGet(); 
        lHttpGet.setURI(lUri); 

        // Sends the request and read the response 
        HttpResponse lHttpResponse = lHttpClient.execute(lHttpGet); 
        InputStream lInputStream = lHttpResponse.getEntity().getContent(); 
        int status = lHttpResponse.getStatusLine().getStatusCode(); 

        /* Get a SAXParser from the SAXPArserFactory. */ 
        SAXParserFactory spf = SAXParserFactory.newInstance(); 
        spf.setNamespaceAware(true); 
        SAXParser sp = spf.newSAXParser(); 

        /* Get the XMLReader of the SAXParser we created. */ 
        XMLReader xr = sp.getXMLReader(); 
        if(type == JaappApplication.QUESTIONS) { 
         xr.setContentHandler(questionHandler); 
        } 


        /* Create a new ContentHandler and apply it to the XML-Reader */ 

        /* Parse the xml-data from our URL. */ 

        if (!((status >= 200) && (status < 300))) { 
        } 
        else 
        { 
         InputSource is = new InputSource(lInputStream); 
         is.setEncoding("ISO-8859-1"); 
         xr.parse(is); 

        } 
        /* Parsing has finished. */ 
        return JaappApplication.SUCCESS; 
       } 
       catch(UnknownHostException e) 
       { 
        Log.e(TAG, e.toString()); 
        return JaappApplication.FAIL; 
       } 
       catch (Exception e) { 
        /* Display any Error to the GUI:. */ 
        Log.e(TAG, e.toString()); 
        return JaappApplication.FAIL; 
       } 

      } 

      public int parseXml(InputStream is, int type) { 
       try { 
        /* Get a SAXParser from the SAXPArserFactory. */ 
        SAXParserFactory spf = SAXParserFactory.newInstance(); 
        spf.setNamespaceAware(true); 
        SAXParser sp = spf.newSAXParser(); 

        /* Get the XMLReader of the SAXParser we created. */ 
        XMLReader xr = sp.getXMLReader(); 
        if(type == JaappApplication.QUESTIONS) { 
         xr.setContentHandler(questionHandler); 
       // } else if(type == NRTApplication.BOTTOMAD) { 
       //  xr.setContentHandler(myBottomAdHandler);  
        } 

        /* Create a new ContentHandler and apply it to the XML-Reader */ 

        /* Parse the xml-data from our URL. */ 
        InputSource is1 = new InputSource(is); 
        is1.setEncoding("ISO-8859-1"); 
        xr.parse(is1); 
        /* Parsing has finished. */ 
        return JaappApplication.SUCCESS; 
       } 
       catch(UnknownHostException e) 
       { 
        Log.e(TAG, e.toString()); 
        return JaappApplication.FAIL; 
       } 
       catch (Exception e) { 
        /* Display any Error to the GUI:. */ 
        Log.e(TAG, "Exception XML parser: " + e.toString()); 
        return JaappApplication.FAIL; 
       } 

      } 


      public ArrayList<QuestionsDto> getQuestions() { 
       return questionHandler.getQuestions(); 
      } 



     } 












     package com.jaapp.xmlparsing; 

     import java.util.ArrayList; 

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

     import android.util.Log; 

     import com.jaapp.dto.QuestionsDto; 

     public class QuestionsReader extends DefaultHandler { 
      private static final String TAG = QuestionsReader.class.getCanonicalName(); 
      private String tempVal; 
      private ArrayList<QuestionsDto> completeQuestionsList; 
      private QuestionsDto tempQues; 

      public QuestionsReader() { 
       completeQuestionsList = new ArrayList<QuestionsDto>(); 
      } 

      @Override 
      public void startDocument() throws SAXException { 
      } 

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

      @Override 
      public void startElement(String uri, String localName, String qName, 
        Attributes attributes) throws SAXException { 
       if (localName.equalsIgnoreCase("question")) { 
        tempQues = new QuestionsDto(); 
       } 
       tempVal = ""; 
      } 

      @Override 
      public void characters(char[] ch, int start, int length) 
        throws SAXException { 
       tempVal += new String(ch, start, length); 
      } 

      @Override 
      public void endElement(String uri, String localName, String qName) 
        throws SAXException { 
       if (localName.equalsIgnoreCase("question")) { 
        completeQuestionsList.add(tempQues); 
       } else if(localName.equalsIgnoreCase("id")) { 
        tempQues.setQid(tempVal); 
       } else if(localName.equalsIgnoreCase("level")) { 
        tempQues.setQlevel(Integer.parseInt(tempVal)); 
       } else if(localName.equalsIgnoreCase("description")) { 
        tempQues.setQquestion(tempVal); 
       } 
      } 

      public ArrayList<QuestionsDto> getQuestions() { 
       return completeQuestionsList; 
      } 
     } 
관련 문제