Reputation: 20658
I have read many articles about XML parsing in Android. However, all of them are just code without any explaination. I'm new to Android (and even Java), however, I have been with .NET for a long time. So please explain me some classes:
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
What do they do?
xr.parse(new InputSource(sourceUrl.openStream()));
This parse a XML file from the Internet. How can I parse a XML file in res/raw? And even with a XML file in SD Card?
Is there any class like XMLDocument in .NET? And how can I write XML file into SD Card?
Thank you.
Upvotes: 0
Views: 507
Reputation: 14438
what might help you out to know is that you can easily also pass a standard string containing XML into the XML Handler intsead of providing a input stream from URL. This might help where you wanted to open some XML string from SD card or any file etc.
you can simply do something like this:
xr.parse(new InputSource(Utils.stringToInputStream(xmlString)));
in my Utils.java file class simply method to convert string to InputStream:
public static InputStream stringToInputStream(String str) throws UnsupportedEncodingException {
return new ByteArrayInputStream(str.getBytes("UTF-8"));
}
Also i know you say you've read many tutorials but i found this tutorial very helpful.
Hope that helps
Upvotes: 0
Reputation: 30934
The first three lines just set up an XML parser. The variant of parser is a stream parser, that does not need the full input as a tree in memory (that would be a dom parser), but which reads the xml data as it streams by.
Do read stuff from the assets folder you could use that code:
AssetManager assetManager = context.getAssets();
try {
InputStream is = assetManager.open("1.xml");
board = new Board();
board.loadFromXmlInputStream(is);
is.close();
where board.loadFromXmlInputStream(is);
internally calls your above 3 lines of code and then xr.parse(new InputSource(is)
See e.g. SampleView for the above lines and the Board.
Note that your code above will not be enough to process the XML - you also need some callbacks (like the ones shown in the Board class).
As an alternative you can also use a DOM parser, that creates a tree representation of the XML in memory that you can then walk.
Upvotes: 1