2013-11-23 179 views
1

我想讀取一個帶有120個項目的Xml文件。閱讀Android上的Xml文件

<?xml version="1.0" encoding="utf-8"?> 
<books> 
     <Book> 
      <bookName >Libro 1</bookName> 
      <bookSection>Unidad 1</bookSection> 
      <memorization>[A long string of information]…</memorization> 
     </Book> 
     <Book>.....</Book> 
</books> 

在我的Android應用我希望把所有這些信息在ArrayList<book>

所以在無效的onCreate我這樣做:

Resources res = getResources(); 
XmlResourceParser x = res.getXml(R.xml.textos); 
     try { 
      insertXML(x); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } catch (XmlPullParserException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

和InsertXML這個樣子。

private void insertXML(XmlPullParser x) throws XmlPullParserException, IOException {   
     try { 

      int eventType = x.getEventType(); 

      while (eventType != XmlPullParser.END_DOCUMENT) { 

       Textos seleccion = new Textos(); 

       if (eventType == XmlPullParser.START_TAG) { 
        if (x.getAttributeValue(null, "Book") != null) { 
         seleccion.setBook(x.getAttributeValue(null, "bookName")); 
         seleccion.setSection(x.getAttributeValue(null, "bookSection")); 
         seleccion.setMemorization(x.getAttributeValue(null, "memorization")); 
        } 

       } 

       if (eventType == XmlPullParser.END_TAG) { 
        if (x.getName().equals("Book")) { 
         texto.add(seleccion); 
        } 
       } 

       eventType = x.next(); 
      } 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

這犯了一個錯誤,因爲在if (x.getAttributeValue(null, "Book") != null) {

永遠不會當我使用調試模式告訴我,x.depth() = 0

那麼,什麼是我做錯了什麼?

回答

1

Book不是一個屬性 - 它是一個元素(標籤)。您應該使用:

if (x.getName().equals("Book")) 

檢查是否是在Book元素。但是,這並不會真正幫助您,因爲您實際上是在bookNamebookSectionmemorization標記之後。我懷疑你真正想要的(檢查爲START_TAG事件中):

if (x.getName().equals("bookName")) { 
    seleccion.setBook(x.nextText()); 
} else if (x.getName().equals("bookSection")) { 
    seleccion.setSection(x.nextText()); 
} else if (x.getName().equals("memorization")) { 
    seleccion.setMemorization(x.nextText()); 
} 

理解的元素和屬性之間的區別是很重要的。例如,在:

<x y="z">Foo</x> 

元件<x>y是具有"z"值的屬性,並且Foox元素中的文本。

+0

感謝喬恩,幫助我一點點,但我的想法是把XML的所有信息在一個ArrayList中 Textos是3串(圖書,科,背誦) 所以,現在我不知道該如何爲類繼續吧。 有幫助嗎? –

+0

@David_Garcia:好吧,我已經幫助你從XML拉解析器中提取信息。如果你陷入其他問題,這聽起來像是一個不同的問題。無論如何,是否有任何理由在這裏使用pull語法分析器?我懷疑,使用DOM API會更容易。 –

+0

我正在閱讀,現在和我使用DOM API,它更好,並修復我所有的問題 感謝您的幫助! –