我正在尝试解析 xml 文件:
<?xml version="1.0"?>
<root>
<command>
<word>cancel</word>
<explanation>cancel print requested with lp</explanation>
</command>
<command>
<word>cat file</word>
<explanation>Display the file</explanation>
</command>
</root>
我为此使用 XML 拉解析器。我的程序是
package com.example.androidsample2;
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 {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView myXmlContent = (TextView)findViewById(R.id.my_xml);
String stringXmlContent;
try {
stringXmlContent = getEventsFromAnXML(this);
myXmlContent.setText(stringXmlContent);
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String getEventsFromAnXML(Activity activity)
throws XmlPullParserException, IOException
{
StringBuffer stringBuffer = new StringBuffer();
Resources res = activity.getResources();
XmlResourceParser xpp = res.getXml(R.xml.xmlfile);
xpp.next();
int eventType = xpp.getEventType();
String tag;
while ((eventType = xpp.next()) != XmlPullParser.END_DOCUMENT)
{
if(XmlPullParser.START_TAG==eventType)
{
tag=xpp.getName();
//stringBuffer.append("\n"+tag);
if(tag=="word")
{
eventType=xpp.next();
stringBuffer.append("\n"+xpp.getText().toString());
}
}
}
return stringBuffer.toString();
}
}
如何使用“word”获得“解释”。即如何使用“cancel”获得“cancel print requests with lp”?