SAXParser with local XML file

2019-09-05 06:20发布

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

3条回答
孤傲高冷的网名
2楼-- · 2019-09-05 07:01

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'.

查看更多
老娘就宠你
3楼-- · 2019-09-05 07:06

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());
查看更多
Rolldiameter
4楼-- · 2019-09-05 07:06
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();
        }
查看更多
登录 后发表回答