我正在尝试使用拉解析来解析本地 XML 的特定部分,但是我不确定我是如何阅读这些部分的。我正在使用代码:
package com.example.xmltest;
import java.io.IOException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.app.Activity;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView myXmlContent = (TextView)findViewById(R.id.xml_tv);
String stringXmlContent;
stringXmlContent = getAllXML();
myXmlContent.setText(stringXmlContent);
}
public String getAllXML(){
Activity activity = this;
String str = "";
Resources res = activity.getResources();
XmlResourceParser xpp = res.getXml(R.xml.ensaheehint);
try {
xpp.next();
int eventType = xpp.getEventType();
System.out.println("eventType : " + eventType);
while (eventType != XmlPullParser.END_DOCUMENT)
{
if(eventType == XmlPullParser.START_DOCUMENT){
str += "nXML Parsing Starting...n";
}
else if(eventType == XmlPullParser.START_TAG)
{
eventType = xpp.next();
if(eventType == XmlPullParser.TEXT){
String text = xpp.getName();
str += "**TEXT: "+text;
}
}
else if(eventType == XmlPullParser.END_TAG)
{
str += "nending tag: "+xpp.getName();
}
else if(eventType == XmlPullParser.TEXT)
{
str += "nvalue : "+xpp.getText();
}
eventType = xpp.next();
}
str += "nnXML parsing Ending......";
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
下面是我的 XML 文件的样子: 我试图一次访问位于 aya 中的一个文本字符串。
<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>