2012-02-11 6 views
1

私はAndroid(およびJavaでも)の新機能ですが、今ではWebサービスで作業を開始しています。SAXparserを使用して複数の要素に情報を取得する(Android)

http://www.anddev.org/novice-tutorials-f8/parsing-xml-from-the-net-using-the-saxparser-t353.html

この例で使用されるXML付::

<outertag> 
<innertag sampleattribute="innertagAttribute"> 
<mytag>anddev.org rulez =)</mytag> 
<tagwithnumber thenumber="1337"/> 
</innertag> 
</outertag> 

私はそれがどのように動作するかを理解する

だから、XMLを解析する方法をよりよく理解するために、私はこのチュートリアルを試して始めました(私が推測する)が、XMLがこのようなものであれば:

<outertag> 
<innertag sampleattribute="innertagAttribute"> 
<mytag>anddev.org rulez =)</mytag> 
<tagwithnumber thenumber="1337"/> 
</innertag> 
<innertag sampleattribute="innertagAttribute2"> 
<mytag>something</mytag> 
<tagwithnumber thenumber="14214"/> 
</innertag> 
</outertag> 

さまざまな要素のデータを取得するために、アプリケーションのクラスを変更する必要はありますか?私はどんな暗示に感謝

...

完全なソースコード:

  • ParseXML.java

    パッケージorg.anddev.android.parsingxml。

    import java.net.URL;

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

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

    輸入android.app.Activity。 import android.os.Bundle; インポートandroid.util.Log; import android.widget.TextView;

    パブリッククラスParsingXMLアクティビティ{

    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. */ 
         URL url = new URL("http://www.anddev.org/images/tut/basic/parsingxml/example.xml"); 
    
         /* 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. */ 
         ParsedExampleDataSet parsedExampleDataSet = 
               myExampleHandler.getParsedData(); 
    
         /* Set the result to be displayed in our GUI. */ 
         tv.setText(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); 
    } 
    

    }

  • ExampleHandler

    パッケージorg.anddev.android.parsingxmlを拡張します。

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

    パブリッククラスExampleHandlerはた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 namespaceURI, String localName, 
         String qName, Attributes atts) throws SAXException { 
        if (localName.equals("outertag")) { 
         this.in_outertag = true; 
        }else if (localName.equals("innertag")) { 
         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, start, length)); 
        } 
    } 
    

    }

  • ParsedExampleDataSet

    パッケージorg.anddev.androidを拡張します。parsingxml;

    パブリッククラス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 "ExtractedString = " + this.extractedString 
          + "nExtractedInt = " + this.extractedInt; 
    } 
    

    }

答えて

2

問題!

ベローは、有用な情報を持つサイトです:私の最初の問題は、私はデータのクラスを定義する方法でした

  • http://www.anddev.org/novice-tutorials-f8/parsing-xml-from-the-net-using-the-saxparser-t353.html
    • https://stackoverflow.com/a/4828765
    • https://stackoverflow.com/a/5709544
    • http://as400samplecode.blogspot.com/2011/11/android-parse-xml-file-example-using.html
    • XMLから抽出したいと思っていました。どのようにすればよいか分かったところで、ExampleHandlerから返されるデータの型をArrayList < "返すデータのクラス"に変更しました。

      私は例の下に与える:あなたが解析したいXMLの

      • 例:

        <outertag> 
        <cartag type="Audi"> 
            <itemtag name="model">A4</itemtag> 
            <itemtag name="color">Black</itemtag> 
            <itemtag name="year">2005</itemtag> 
        </cartag> 
        <cartag type="Honda"> 
            <itemtag name="model">Civic</itemtag> 
            <itemtag name="color">Red</itemtag> 
            <itemtag name="year">2001</itemtag> 
        </cartag> 
        <cartag type="Seat"> 
            <itemtag name="model">Leon</itemtag> 
            <itemtag name="color">White</itemtag> 
            <itemtag name="year">2009</itemtag> 
        </cartag> 
        </outertag> 
        

      をだからここにあなたが適切な属性を持つクラス "車" を定義する必要があります(文字列型、モデル、色、年;)、セッターとゲッタ...

      • このXMLのためのExampleHandlerの私の提案は次のとおりです。

      パブリッククラスExampleHandlerは、あなたが活動に解析されたデータを使用して取得することができたDefaultHandler {

      // =========================================================== 
      // Fields 
      // =========================================================== 
      
      private int numberOfItems=3;  
      private boolean in_outertag = false; 
      private boolean in_cartag = false; 
      private boolean[] in_itemtag = new boolean[numberOfItems]; 
      
      Car newCar = new Car(); 
      
      private ArrayList<Car> list = new ArrayList<Car>(); 
      
      // =========================================================== 
      // Getter & Setter 
      // =========================================================== 
      
      public ArrayList<Car> getParsedData() { 
          return this.list; 
      } 
      
      // =========================================================== 
      // Methods 
      // =========================================================== 
      @Override 
      public void startDocument() throws SAXException { 
          this.list = new ArrayList<Car>(); 
      } 
      
      @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 namespaceURI, String localName, 
           String qName, Attributes atts) throws SAXException { 
          if (localName.equals("outertag")) { 
           this.in_outertag = true; 
          }else if (localName.equals("cartag")) { 
           this.in_cartag = true; 
           newCar.setType(atts.getValue("type")); //setType(...) is the setter defined in car class 
          }else if (localName.equals("itemtag")) { 
           if((atts.getValue("name")).equals("model")){ 
            this.in_itemtag[0] = true; 
           }else if((atts.getValue("name")).equals("color")){ 
            this.in_itemtag[1] = true; 
           }else if((atts.getValue("name")).equals("year")){ 
            this.in_itemtag[2] = true; 
           } 
          } 
      } 
      
      /** 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("cartag")) { 
           this.in_cartag = false; 
           Car carTemp = new Car(); 
           carTemp.copy(newCar, carTemp); //this method is defined on car class, and is used to copy the 
                   //properties of the car to another Object car to be added to the list 
           list.add(carTemp); 
          }else if (localName.equals("itemtag")){ 
           if(in_itemtag[0]){ 
            this.in_itemtag[0] = false; 
           }else if(in_itemtag[1]){ 
            this.in_itemtag[1] = false; 
           }else if(in_itemtag[2]){ 
            this.in_itemtag[2] = false; 
           } 
          } 
      } 
      
      /** Gets be called on the following structure: 
      * <tag>characters</tag> */ 
      @Override 
      public void characters(char ch[], int start, int length) { 
      
          if(in_itemtag[0]){ 
           newCar.setModel(new String(ch, start, length)); 
          }else if(in_itemtag[1]){ 
           newCar.setColor(new String(ch, start, length)); 
          }else if(in_itemtag[2]){ 
           newCar.setYear(new String(ch, start, length)); 
          } 
      } 
      

      }この後

      を拡張:

      ... 
      ArrayList<Car> ParsedData = myExampleHandler.getParsedData(); 
      ... 
      

      私はこれが誰かを助けてくれることを願っています。

      注意:スタックに私は...

      そして、私の悪い英語のため申し訳ありませんが、まさにこのようにテストしたが、それは動作するはずですので、ほとんど私の解決策と同じである持っていない...

    +1

    ようこそオーバーフロー!将来的にサイトが古くなる可能性があるので、単に別のサイトへのリンクを回答として与えるべきではありません。代わりに、この回答の「編集」リンクをクリックして、そのページのソリューションの重要な部分をここに含めます。参照してください:http://meta.stackexchange.com/q/8259 –

    +0

    既に編集;)私はこの方法がより良いことを望む。 – amp

    関連する問題