Reputation: 209
I am trying to parse the xml file:
<?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>
I am using XML pull parser for this.My program is
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();
}
}
How can i obtain the "explanation" by using "word".i.e how can i obtain "cancel print requested with lp" by using "cancel"?
Upvotes: 2
Views: 776
Reputation: 78905
The following line might work in C# but not in Java:
if(tag=="word")
Instead, write:
if (tag.equals("word"))
Update:
String word = null;
while ((eventType = xpp.next()) != XmlPullParser.END_DOCUMENT)
...
if (tag.equals("word"))
{
eventType = xpp.next();
word = xpp.getText();
}
else if (tag.equals("explanation"))
{
eventType = xpp.next();
if ("cancel".equals(word))
{
stringBuffer.append("\n" + xpp.getText());
}
}
Upvotes: 4