Can anyone tell me how to parse a local XML file stored in the system using SAX, with an exampl开发者_如何转开发e 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
}
package com.xml; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import android.util.Log; import android.widget.Toast; public class FeedHandler extends DefaultHandler { StringBuilder sb = null; String ret = ""; boolean bStore = false; int howMany = 0; FeedHandler() { } String getResults() { return "XML parsed data.\nThere are [" + howMany + "] status updates\n\n" + ret; } @Override public void startDocument() throws SAXException { // initialize "list" } @Override public void endDocument() throws SAXException { } @Override public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { try { if (localName.equals("status")) { this.sb = new StringBuilder(""); bStore = true; } if (localName.equals("user")) { bStore = false; } if (localName.equals("text")) { this.sb = new StringBuilder(""); Log.i("sb ", sb+""); } if (localName.equals("created_at")) { this.sb = new StringBuilder(""); } } catch (Exception e) { Log.d("error in startElement", e.getStackTrace().toString()); } } @Override public void endElement(String namespaceURI, String localName, String qName) throws SAXException { if (bStore) { if (localName.equals("created_at")) { ret += "Date: " + sb.toString() + "\n"; sb = new StringBuilder(""); return; } if (localName.equals("user")) { bStore = true; } if (localName.equals("text")) { ret += "Post: " + sb.toString() + "\n\n"; sb = new StringBuilder(""); return; } } if (localName.equals("status")) { howMany++; bStore = false; } } @Override public void characters(char ch[], int start, int length) { if (bStore) { // System.out.println("start " +start+"length "+length); String theString = new String(ch, start, length); this.sb.append(theString+"start "+start+" length "+length); } } }
InputSource is = new InputSource(getResources().openRawResource(R.raw.my)); System.out.println("running xml file..... "); // create the factory SAXParserFactory factory = SAXParserFactory.newInstance(); // create a parser SAXParser parser = factory.newSAXParser(); // create the reader (scanner) XMLReader xmlreader = parser.getXMLReader(); // instantiate our handler FeedHandler fh = new FeedHandler(); // assign our handler xmlreader.setContentHandler(fh); // perform the synchronous parse xmlreader.parse(is); // should be done... let's display our results tvData.setText(fh.getResults());
sample code
Create documentBuilderFactory
DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
- Create DocumentBuilder
DocumentBuilder builder=factory. newDocumentBuilder();
- get input stream
ClassLoader cls=DomReader.class.getClassLoader();
InputStream is=cls.getResourceAsStream("xml file");
- parse xml file and get Document object by calling parse method on DocumentBuilder object. Document document=builder.parse(is);
- Traverse dom tree using document object. SAX: Simple xml parsing. It parses node by node Traversing is from top to bottom Low memory usage Back navigation is not possible with sax.
//implementing required handlers public class SaxParse extends DefaultHandler{ } //new instance of saxParserFactory SAXParserFactory factory=SAXParserFactory.newInstance(); //NEW INSTANCE OF SAX PARSER SAXParser saxparser=factory.newSAXParser(); //Parsing xml document SAXParser.parse(new File(file to be parsed), new SAXXMLParserImpl());
精彩评论