2013-05-07 3 views
0

Как я могу разобрать локальный XML-файл, чтобы иметь возможность вводить его строковые значения в методе TextView.setText(String)? Мой локальный файл XML выглядит следующим образом:Анализ индексированных XML в Android

<quran> 
<sura index="1" name="الفاتحة"> 
    <aya index="1" text="In the name of Allah, the Entirely Merciful, the Especially Merciful."/> 
    <aya index="2" text="[All] praise is [due] to Allah, Lord of the worlds -"/> 
    <aya index="3" text="The Entirely Merciful, the Especially Merciful,"/> 
    <aya index="4" text="Sovereign of the Day of Recompense."/> 
    <aya index="5" text="It is You we worship and You we ask for help."/> 
    <aya index="6" text="Guide us to the straight path -"/> 
    <aya index="7" text="The path of those upon whom You have bestowed favor, not of those who have evoked [Your] anger or of those who are astray."/> 
</sura> 
<sura index="2" name="البقرة"> 
    <aya index="1" text="Alif, Lam, Meem."/> 
    <aya index="2" text="This is the Book about which there is no doubt, a guidance for those conscious of Allah -"/> 
    <aya index="3" text="Who believe in the unseen, establish prayer, and spend out of what We have provided for them,"/> 
    <aya index="4" text="And who believe in what has been revealed to you, [O Muhammad], and what was revealed before you, and of the Hereafter they are certain [in faith]."/> 
    <aya index="5" text="Those are upon [right] guidance from their Lord, and it is those who are the successful."/> 

Я хочу, чтобы иметь возможность доступа к конкретному текстовых строк, расположенные в определенных индексах AYH, но я не знаю, как это сделать, так как для каждого объекта в пределах аи объект суры есть две вещи: индекс и текст, который я хочу получить. Пожалуйста помоги!

+0

использование XML-парсера –

+0

Любая идея, как я иду об этом специально для этого файла или хороший учебник? Мне нужно иметь доступ к одной строке за раз, вроде поиска. Пользователь вводит местоположение и строку, помещенную в TextView. –

+0

Мне нравится [этот учебник] (http://www.ibm.com/developerworks/opensource/library/x-android/). Он просматривает все общие синтаксические анализаторы и сравнивает их все, чтобы вы знали, какой из них подходит вам. –

ответ

0

Если вы хотите использовать XmlPullParser, как предлагает Harsh, посмотрите пример, приведенный в обзоре классов в [docs] [1].

Это «текст» атрибут в элементах «Ая», которые вы хотите, поэтому вы должны использовать метод XmlPullParser.getAttributeValue(null, "text"), как показано ниже:

XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); 
factory.setNamespaceAware(true); 
XmlPullParser xpp = factory.newPullParser(); 

xpp.setInput(new StringReader ("<quran><sura index=\"1\" name=\"الفاتحة\"><aya index=\"1\" text=\"In the name of Allah, the Entirely Merciful, the Especially Merciful.\"/><aya index=\"2\" text=\"[All] praise is [due] to Allah, Lord of the worlds -\"/><aya index=\"3\" text=\"The Entirely Merciful, the Especially Merciful,\"/><aya index=\"4\" text=\"Sovereign of the Day of Recompense.\"/><aya index=\"5\" text=\"It is You we worship and You we ask for help.\"/><aya index=\"6\" text=\"Guide us to the straight path -\"/><aya index=\"7\" text=\"The path of those upon whom You have bestowed favor, not of those who have evoked [Your] anger or of those who are astray.\"/></sura><sura index=\"2\" name=\"البقرة\"><aya index=\"1\" text=\"Alif, Lam, Meem.\"/><aya index=\"2\" text=\"This is the Book about which there is no doubt, a guidance for those conscious of Allah -\"/><aya index=\"3\" text=\"Who believe in the unseen, establish prayer, and spend out of what We have provided for them,\"/><aya index=\"4\" text=\"And who believe in what has been revealed to you, [O Muhammad], and what was revealed before you, and of the Hereafter they are certain [in faith].\"/><aya index=\"5\" text=\"Those are upon [right] guidance from their Lord, and it is those who are the successful.\"/></sura></quran>")); 
int eventType = xpp.getEventType(); 
while (eventType != XmlPullParser.END_DOCUMENT) { 
    if(eventType == XmlPullParser.START_DOCUMENT) { 
     Log.i(getClass().getName(), "Start document"); 
    } else if(eventType == XmlPullParser.START_TAG) { 
     Log.i(getClass().getName(), "Start tag "+xpp.getName()); 
     if(xpp.getName().equals("aya")){ 
      Log.i(getClass().getName(), "aya text: " + xpp.getAttributeValue(null, "text")); 
     } 
    } else if(eventType == XmlPullParser.END_TAG) { 
     System.out.println("End tag "+xpp.getName()); 
     Log.i(getClass().getName(), "End tag "+xpp.getName()); 
    } else if(eventType == XmlPullParser.TEXT) { 
     System.out.println("Text "+xpp.getText()); 
     Log.i(getClass().getName(), "Text "+xpp.getText()); 
    } 
    eventType = xpp.next(); 
} 
Log.i(getClass().getName(), "End document"); 
+0

Спасибо! Ваше решение помогло мне туда добраться! К сожалению, в течение долгого времени не было времени. :) –

Смежные вопросы