开发者

How to Pass a XML File to a XMLReader

Previously in my Android project I passed a URL String (Web Address) to the XMLReader to parse. But now I want to pass the XML File from my the project itself for this purpose.

  1. Where should I place the XML File (Note:- After installing it on a device, I expect to update the contents of the XML File weekly. Placement of the XML File should be flexible for this)
  2. How can I retrieve data from the XML File to the XMLReader

Previous (Working)

        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();

        URL sourceUrl;

        sourceUrl = new URL(
        "http://www.a开发者_运维知识库ndroidpeople.com/wp-content/uploads/2010/06/example.xml");


        XMLHandler myXMLHandler = new XMLHandler();
        xr.setContentHandler(myXMLHandler);
        xr.parse(new InputSource(sourceUrl.openStream()));


To answer your second question, you can construct an InputSource from a FileInputStream, similar to what you are doing with the url. I suggest to also set the systemId to get nicer error reporting and in case you need to resolve relative paths from the xml.

InputStream in = new FileInputStream(file);
try {
    InputSource is = new InputSource(in);
    is.setSystemId(file.getAbsolutePath());
    xr.parse(is);
} finally {
    in.close();
}


With respect to your first question, you can store the file directly onto the Android phone. Some nice tutorials for that at Hello Android and Skill Guru. To illustrate some of the code below:

String aFileName = "mydata.xml";

// An output stream
FileOutputStream fos = context.openFileOutput(aFileName, context.MODE_PRIVATE);

//An input stream
FileInputStream fis = openFileInput(FILE_NAME);

For your second question, as has already been suggested, you just create an input source from the file input stream you got in step 1, and your good to go.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜