XML in the development of the role can not be underestimated, many times we have to use this file, so learning its analytic way is very necessary.
We all know that the parsing of XML in Java is: Dom,sax, but under Android we use Pool parsing, is more convenient, and has a dedicated API can be used.
DOM: Load into memory at once, generate a tree structure, consume large memory
SAX: Event-based, fast, high-efficiency, and cannot be rolled back.
1, first we need to define the parser, the way it is defined, is through the XML new, this should be remembered.
Xmlpullparser parser = Xml.newpullparser ();
2, then we need to set the XML file source, that is, initialize the parser, using the method as follows, and we also have to set the encoding format, XML encoding is generally "utf-8", so the second parameter we write "Utf-8", and the first argument, if our XML in local words , we can come through the class loader and its return type is InputStream.
Parser.setinput (InputStream InputStream, String inputencoding)
The ClassLoader gets the location of the file and returns InputStream.
MainActivity.class.getClassLoader (). getResourceAsStream ("XML file Path")
3, after initializing the parser, we can start with a lot of XML tags, here, we need to call the method is.
int type = Parser.geteventtype ();
We look at the API and we get a label,
For example: (This is the definition in the system)
int start_document = 0;
int end_document = 1;
int start_tag = 2;
int end_tag = 3;
From the first name we can easily know its meaning, the XML start and end tag, and the beginning and end of a label pair.
So we can compare the obtained type with these tags so that we can get the value of the tag.
4, parsing xml
while(Type! =xmlpullparser.end_document) { Switch(type) { CaseXmlpullparser.start_tag:if("Infos". Equals (Parser.getname ())) { //resolves to the global start tag. Weatherinfos =NewArraylist<weatherinfo>(); } Else if("City". Equals (Parser.getname ())) {Weatherinfo=NewWeatherinfo (); //Get IDString id = parser.getattributevalue (0); Weatherinfo.setid (Integer.parseint (id)); } Else if("Temp". Equals (Parser.getname ())) {String temp=Parser.nexttext (); Weatherinfo.settemp (temp); } Break; CaseXmlpullparser.end_tag:if("City". Equals (Parser.getname ())) { //the information of a city has been processed. Weatherinfos.add (Weatherinfo); Weatherinfo=NULL; } Break; } type=Parser.next (); }
After parsing the XML, we also want to save its value, so I put the value of each XML parse into the collection,
Here are some points to note,
Parser.getattributevalue (0); is to get the ID value in the tag.
After each parsing, we have to move the loop down, so type = parser.next ();
So that we can parse out the data in the XML.
Darren
Weibo: @IT_ Siege Division
Source: http://www.cnblogs.com/fengtengfei/
Android Development Pool Parsing xml