Can anyone tell me how to parse a local XML file stored in the system using SAX, with an example code? Please also tell me where can I find information on that.
To read from XML in your app, create a folder in your res folder inside your project called "xml" (lower case). Store your xml in this newly created folder. To load the XML from your resources,
XmlResourceParser myxml = mContext.getResources().getXml(R.xml.MyXml);//MyXml.xml is name of our xml in newly created xml folder, mContext is the current context
// Alternatively use: XmlResourceParser myxml = getContext().getResources().getXml(R.xml.MyXml);
myxml.next();//Get next parse event
int eventType = myxml.getEventType(); //Get current xml event i.e., START_DOCUMENT etc.
You can then start to process nodes, attributes etc and text contained within by casing the event type, once processed call myxml.next() to get the next event, i.e.,
String NodeValue;
while (eventType != XmlPullParser.END_DOCUMENT) //Keep going until end of xml document
{
if(eventType == XmlPullParser.START_DOCUMENT)
{
//Start of XML, can check this with myxml.getName() in Log, see if your xml has read successfully
}
else if(eventType == XmlPullParser.START_TAG)
{
NodeValue = myxml.getName();//Start of a Node
if (NodeValue.equalsIgnoreCase("FirstNodeNameType"))
{
// use myxml.getAttributeValue(x); where x is the number
// of the attribute whose data you want to use for this node
}
if (NodeValue.equalsIgnoreCase("SecondNodeNameType"))
{
// use myxml.getAttributeValue(x); where x is the number
// of the attribute whose data you want to use for this node
}
//etc for each node name
}
else if(eventType == XmlPullParser.END_TAG)
{
//End of document
}
else if(eventType == XmlPullParser.TEXT)
{
//Any XML text
}
eventType = myxml.next(); //Get next event from xml parser
}