I'm sorry, my friend has been married for a few days. The next few days will be updated normally. Bring XML file parsing today

Source: Internet
Author: User

Three kinds of analytic methods dom,sax,xmlpullparse; You think I'm going to say three kinds of wrong, I only say one, the other two I just said the pros and cons,

One, Dom parser

Advantages:

When parsing an XML document, the DOM parser parses all the elements in the document into a Node object (nodes) according to the hierarchical relationships that appear. The node object provides a list of types of represented representing nodes
, when the developer obtains a node type, the node node can be converted to the corresponding nodes object (the child object of node), so that its unique method is called.
The node object provides a way to get its parent node or child node. These methods allow programmers to read the contents of an entire XML document, or to add, modify, or delete the contents of an XML document.

Disadvantages:


It takes a lot of memory to fully load the entire XML file at once.

Second, SAX

Pros: Sax parsing allows documents to be processed when they are read, without having to wait until the entire document is loaded before the document is manipulated.

Third, Pullparse

Pull parse XML file step:


1. Write an XML file yourself, save some weather information


# # #拿到xml文件

InputStream is = getClassLoader (). getResourceAsStream ("Weather.xml");


# # #拿到pull解析器

Xmlpullparser XP = Xml.newpullparser ();

2. Start parsing
Get the event type of the current node where the pointer is located

int type = Xp.geteventtype ();
There are five main types of events
Event types for Start_document:xml headers
Type of event End_document:xml tail
Start_tag: Event type of the start node
End_tag: Event type for end node
Text: The event type of the literal node

If the obtained event type is not end_document, then the parsing is not complete, and if it is, the parsing is complete and the while loop ends

while (type! = xmlpullparser.end_document)
When we resolve to different nodes, we need to do different things, so we can judge the name of the current node.
When parsing to the start node of weather, the new list
When resolving to the start node of city, the city object is created and the object is created to make it easier to save the text that will be parsed
When parsing to the name start node, gets the text content of the next node, same as temp, PM

Case Xmlpullparser.start_tag:
Gets the name of the current node
if ("Weather". Equals (Xp.getname ())) {
Citys = new arraylist<city> ();
}
else if ("City". Equals (Xp.getname ())) {
City = new City ();
}
else if ("name". Equals (Xp.getname ())) {
Gets the text of the next node of the current node
String name = Xp.nexttext ();
City.setname (name);
}
else if ("temp". Equals (Xp.getname ())) {
String temp = Xp.nexttext ();
City.settemp (temp);
}
else if ("PM". Equals (Xp.getname ())) {
String pm = Xp.nexttext ();
CITY.SETPM (PM);
}
Break

When resolving to the end node of city, it shows that the city's three child nodes have all been parsed, adding the city object to the list

Case Xmlpullparser.end_tag:
if ("City". Equals (Xp.getname ())) {
Citys.add (city);
}

Write a random xml:

<?xml version= "1.0" encoding= "Utf-8"?><weather>    <city>        <name> Anyang </name>        <temp>-8℃</temp>        <pm25>120</pm25>    </city>    <city>        < Name> Beijing </name>        <temp>-12℃</temp>        <pm25>500</pm25>    </city>    <city>        <name> Shanghai </name>        <temp>2℃</temp>        <pm25>60</ Pm25>    </city></weather>

Define a JavaBean to install name temp PM25:

 PackageCom.ace.pullparser; Public classCity {PrivateString name; PrivateString temp; PrivateString PM25;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicString gettemp () {returntemp; }     Public voidsettemp (String temp) { This. temp =temp; }     PublicString getPm25 () {returnPM25; }     Public voidsetPm25 (String pm25) { This. PM25 =PM25; } @Override PublicString toString () {return"City [name=" + name + ", temp=" + temp + ", pm25=" + PM25 + "]"; }        }

Mainactivity:

 PackageCom.ace.pullparser;ImportJava.io.InputStream;Importjava.util.ArrayList;Importjava.util.List;ImportOrg.xmlpull.v1.XmlPullParser;Importorg.xmlpull.v1.XmlPullParserException;Importcom.itheima.pullparser.domain.City;ImportAndroid.os.Bundle;Importandroid.app.Activity;Importandroid.util.Xml;ImportAndroid.view.Menu;ImportAndroid.view.View; Public classMainactivityextendsActivity {List<City>CityList; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);                    Setcontentview (R.layout.activity_main); }         Public voidClick (View v) {//Get the Weather information XML file (without creating the background, put the XML you created in the SRC directory, getClassLoader (). Getresourcestream is a way to read files in the SRC directory)InputStream is = getClassLoader (). getResourceAsStream ("Weather.xml"); //Get xmlpull parserXmlpullparser XP =Xml.newpullparser (); Try {            //InitializeXp.setinput (IS, "GBK"); //gets the event type of the current node            intType =Xp.geteventtype (); City City=NULL;  while(Type! =xmlpullparser.end_document) {                Switch(type) { CaseXmlpullparser.start_tag://gets the name of the current node                    if("Weather". Equals (Xp.getname ())) {CityList=NewArraylist<city>(); }                    Else if("City". Equals (Xp.getname ())) { City=NewCity (); }                    Else if("Name". Equals (Xp.getname ())) {                                        //gets the text of the next nodeString name =Xp.nexttext ();                    City.setname (name); }                    Else if("Temp". Equals (Xp.getname ())) {                        //gets the text of the next node, moving the pointer to the end node of the current nodeString temp =Xp.nexttext ();                    City.settemp (temp); }                    Else if("PM25". Equals (Xp.getname ())) {                        //gets the text of the next nodeString PM25 =Xp.nexttext ();                    CITY.SETPM25 (PM25); }                     Break;  CaseXmlpullparser.end_tag:if("City". Equals (Xp.getname ()))                    {Citylist.add (city); }                     Break; }                //moves the pointer to the next node and returns the event type for that nodeType =Xp.next (); }        } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); }                 for(city city:citylist) {System.out.println (city.tostring ()); }    }    }

Layout has only one button

    <button        android:layout_width= "Wrap_content"        android:layout_height= "Wrap_content"         Android:text= "Get weather Information"         android:onclick= "click"        />

Although very basic but I slowly write the knowledge to share to the people themselves also review very good is great so I will insist on

I'm sorry, my friend has been married for a few days. The next few days will be updated normally. Bring XML file parsing today

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.