2012-01-17 13 views
4

私は、WebからXMLを解析するAndroidアプリケーションを開始しています。私はいくつかのAndroidアプリを作成しましたが、XMLを解析することは一度もありませんでした。誰かが最善の方法を知りたいと思っていましたか?WebサイトからAndroidデバイスへのXMLの解析

答えて

9

は、ここに例を示します

<numbers> 
    <phone> 
     <string name = "phonenumber1">555-555-5555</string> 
    </phone> 
    <phone> 
     <string name = "phonenumber2">555-555-5555</string> 
    </phone> 
</numbers> 

を、私は "文字列" と "電話" と/*item within the tag*//*tag from xml file*/に代わる:私の例では

 try { 
      URL url = new URL(/*your xml url*/); 
      URLConnection conn = url.openConnection(); 

      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
      DocumentBuilder builder = factory.newDocumentBuilder(); 
      Document doc = builder.parse(conn.getInputStream()); 

      NodeList nodes = doc.getElementsByTagName(/*tag from xml file*/); 
      for (int i = 0; i < nodes.getLength(); i++) { 
       Element element = (Element) nodes.item(i); 
       NodeList title = element.getElementsByTagName(/*item within the tag*/); 
       Element line = (Element) title.item(0); 
       phoneNumberList.add(line.getTextContent()); 
      } 
     } 
     catch (Exception e) { 
      e.printStackTrace(); 
     } 

、私のXMLファイルには、少しのように見えます。

+0

これは私にこのエラーを引き起こしています:http://stackoverflow.com/questions/13270372/ android-os-networkonmainthreadexception-接続しようとしたときに無線で使用する –

1

私は常にw3c domクラスを使用します。私は文字列としてxmlデータを解析するために使用する静的ヘルパーメソッドを持って、私にドキュメントオブジェクトを返します。どこでxmlデータを取得することができますか(ウェブ、ファイルなど)、最終的には文字列としてロードします。

Document document = null; 
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder builder; 

    try 
    { 
     builder = factory.newDocumentBuilder(); 
     InputSource is = new InputSource(new StringReader(data)); 
     document = builder.parse(is); 
    } 
    catch (SAXException e) { } 
    catch (IOException e) { } 
    catch (ParserConfigurationException e) { } 
1

このような

何か...利用可能なメカニズムを解析するさまざまな種類があり、1は第二、SAX Here is SAX parsing exampleあるDOMはHere is DOM Parsing example.を解析しています。あなたの質問から、あなたが望むものは明確ではありませんが、これらは良い出発点かもしれません。

+0

大変ありがとうございます。DOMとSAXの構文解析に当たって時間を掛けてください。(lol – carsey88

0

私はDOMパーサーを使用しますが、XMLファイルが大きすぎない場合はSAXほど効率的ではありません。その場合は簡単です。

私は、XML解析を含むAndroid Appを1つだけ作成しました。 SOAP Webサービスから受信したXML。私はXmlPullParserを使用しました。 Xml.newPullParser()の実装には、約束されたドキュメントのようにnextText()への呼び出しが常にEND_TAGに進まなかったバグがありました。このための回避策があります。

1

DOM、SAX、XMLPullParsingの3種類の構文解析があります。

私の例では、XML要素のURLと親ノードが必要です。

try { 
    URL url = new URL("http://www.something.com/something.xml"); 
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder db = dbf.newDocumentBuilder(); 
    Document doc = db.parse(new InputSource(url.openStream())); 
    doc.getDocumentElement().normalize(); 

    NodeList nodeList1 = doc.getElementsByTagName("parent node here"); 
    for (int i = 0; i < nodeList1.getLength(); i++) { 
     Node node = nodeList1.item(i); 
    } 
} catch(Exception e) { 

} 

また、thisを試してください。

関連する問題