问题
I've read several topic on how to read local XML file.
Most of them are using openRawResource(). However it's much more slower compared to getXML().
I wanted to use getXML for my project, it's there any way to use getXML with XMLReader.parse(), as SAX InputSource does not accept XmlResourceParser as parameter.
Edit: btw, when do the startElement endElement will be called? Is it right after XMLReader.parse? Is it possible to restart the parsing from the top when I read a certain value of attributes?
Thank you very much
回答1:
You can use it(assume that you are keeping your xml in assets folder)
InputStream response=context.getAssets().open("your.xml");
and then
Xml.parse(response, Xml.Encoding.UTF_8,rootElement.getContentHandler());
回答2:
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
MyXMLHandler myXMLHandler = new MyXMLHandler(getApplicationContext());
reader.setContentHandler(myXMLHandler);
reader.parse(new InputSource(getAssets().open("Getalloffersbyzipcoderesponse_xml.xml")));
// listView.setAdapter(new EventListAdapter(getApplicationContext(), 0, myXMLHandler.getEventList()));
listView.setAdapter(new OffersListAdapter(getApplicationContext(), 0, myXMLHandler.getOffersList()));
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
回答3:
If you want to use the 'getXML()'-function, you can check out this tutorial, whic show's how to use the 'XmlResourceParser'-Interface: Link
Anothet way would be if you put the XML files in the 'openRawResource'-method, which returns an 'InputStream' on a given Resource ID, which you can then pass to the normal 'SAXParser'.
来源:https://stackoverflow.com/questions/5948483/saxparser-with-local-xml-file