Traditional Culture Encyclopedia - Weather inquiry - How to parse complex xml files in android
How to parse complex xml files in android
The contents of this document are as follows:
Then it is necessary to parse this XML file. Let's parse this XML file with DOM, SAX and PULL respectively.
DOM mode
Parsing xml with DOM means reading all xml documents into memory first, and then accessing the tree structure with DOM API to obtain data. From the way of DOM parsing, we can know that if the XML file is large, the processing efficiency will be low, which is also a disadvantage of DOM method.
Now let's parse the xml file related to the weather forecast information mentioned above. What is parsing? To put it bluntly, it is to identify this tagged XML file and extract some relevant and useful information for us to use. Then in this file, time, weather, temperature and icons are all what we need. We need to analyze it.
The specific thinking of the analysis is:
1. Load the XML file.
2. Get the root node of the document
3. Get the list of all child nodes in the root node of the document.
4. Obtain the node information to be read in the child node list.
According to these four steps, we develop:
The first is how to load an XML file, assuming that the file comes from the network.
SAX mode
SAX is the abbreviation of simple API of XML. A package can also be regarded as some interfaces.
Compared with DOM, SAX is a faster, more efficient and less memory-intensive method for parsing XML files. It scans line by line and can be parsed while scanning, so SAX can stop parsing at any time when parsing a document. Very suitable for mobile devices such as Android.
SAX is event driven. Event-driven means that you don't need to parse the whole document. In the process of parsing documents in content order, SAX will judge whether the currently read characters conform to a certain part of XML file syntax. If a part is met, an event will be triggered. The so-called trigger event is to call some callback methods. Of course, the event mechanism of android is based on the callback method. When parsing an xml document with SAX, an event will be called back when reading the opening and closing tags of the document, and an event will be called back when reading other nodes and contents. In the SAX interface, the event source is the xmlReader in the org.xml.sax package, which parses the XML document through the parser () method and generates events. The event handlers are four interfaces in the org.xml.sax package: ContentHander, DTDHander, ErrorHandler and EntityResolver.
Details of these four interfaces are as follows:
Event handler name
The event handled by the event handler.
XMLReader registration method
Content processor
The beginning and end of an XML document,
The beginning and end of XML document tags, receiving character data, skipping entities, and receiving negligible blanks in element content.
SetContentHandler (content handler h)
DTDHander
Handles the corresponding events generated during DTD parsing.
setDTDHandler(DTDHandler h)
Error handler
Error while processing XML document.
Set the error handler (error handler h)
EntityResolver
Dealing with external entities
SetEntityResolver (entity solution e)
The callback method we use for content parsing is usually defined in the ContentHandler interface.
Common methods of ContentHandler interface:
startDocument()
Call this method when you meet the beginning of the document, and you can do some preprocessing work in it.
endDocument()
Call this method at the end of the document, and you can do some aftermath in it.
StartElement (string namespaceURI, string localName, string qName, attribute atts)
This method is called when the start tag is read. NamespaceURI is a namespace, localName is a tagname without namespace prefix, and qName is a tagname with namespace prefix. All attribute names and corresponding values can be obtained through atts.
EndElement (string uri, string localName, string name)
This method is called when an end tag is encountered.
Characters (char[] ch, int start, int length)
This method is used to process what is read in an XML file. For example:
The first parameter is used to store the contents of the file, and the last two parameters are the starting position and length of the read string in the array. You can get the content by using the new string (ch, start, length).
note:
An important feature of SAX is its stream processing. When it encounters a tag, it will not record the tag it encountered before, that is, in the startElement () method, all it can know is the name and attributes of the tag. As for the nested structure of the tag, the name of the upper tag, whether there are child tags, and other information related to the structure are unknown and need your program to complete. This makes SAX less convenient than DOM in programming processing.
Now we intercept an XML file for parsing, and its calling method is as follows:
& lt? xml version=" 1.0 "? & gt-& gt; startDocument()
& lt Weather & gt-& gt;; startElement
& lt forecast information & gt-& gt;; startElement
& lt City & gt-& gt;; startElement
Beijing->; trait
& lt/city & gt; -& gt; End element
& lt/forecast _ information & gt; -& gt; End element
& lt/weather & gt; -& gt; End element
End of document -> endDocument ()
Parsing steps of SAX:
The first thing to note is:
SAX also developed a Helper class for it: DefaultHandler, which implements the interface of ContentHandler, but all its method bodies are empty. When implementing, you only need to inherit this class and then overload the corresponding method.
There are five steps in parsing XML files with SAX:
1, create SAXParserFactory object;
2. Call the newSAXParser method in SAXParserFactory to create SAXParser objects;
3. Then get an XMLReader object by calling the getXMLReader method in SAXParser;
4. Instantiate the DefaultHandler object.
5. connect the event source object XMLReader to the event handling class DefaultHandler.
6. Call the parse method of xmlReader to get XML data from the input source.
7. Return the data set we need through DefaultHandler.
Let's still parse the XML file of the weather forecast mentioned above.
Write the code as follows:
[java] View Plain Text
MySAX.setOnClickListener (new button. OnClickListener(){
@ Overlay
Public void onClick (view v)
Try {
String url = "/ig/api? & weather = Beijing ";
default http client client = new default http client();
HttpUriRequest req = new http get(URL);
http response resp = client . execute(req);
HttpEntity ent = resp . get entity();
InputStream stream = ent . get content(); //Import files into the stream, so use InputStream.
SAXParserFactory sax factory = SAXParserFactory . new instance(); //Get an object
sax parser sax parser = sax factory . newsaxparser(); //Create a parser using the obtained object.
XMLContentHandler handler = new XMLContentHandler(); //Set the default handler
SaxParser.parse (stream, handler); //Used for parsing
stream . close(); //Close the stream
/* XML reader XML reader = sax factory . newsaxparser()。 getxml reader(); //get XMLReader
XmlReader.setContentHandler (handler);
XML reader . parse(new input source(stream));
stream . close(); */
}catch (exception e){
e . printstacktrace();
}
}
});
}
Public class XMLContentHandler extends DefaultHandler {
private static final String TAG = " XMLContentHandler ";
@ Overlay
Public null character (char[] ch, int start, int length)
Throw SAXException {
Log.i (tag, "parse content:"+new string (ch, start, length)););
}
@ Overlay
Public void endDocument () throws SAXException {
super . end document();
Log.i (tag, "The document has been parsed." );
}
@ Overlay
Public void endElement (string uri, string localName, string qName)
Throw SAXException {
Log.i(TAG,local name+" Parsed ");
}
@ Overlay
PublicoVoid startdocument () throws SAXException {
Log.i (tag, "Start parsing ..........");
}
@ Overlay
Public void startElement (string uri, string localName, string qName,
Attributesartributes) throws SAXException {
Log.i (tag, "parsing element:"+localname);
if(local name . equals(" high "){
Log.i (tag, "parsing element:"+localname);
i++;
if(i==2){
highesttmp . settext(string . value of((integer . parse int(attributes . getvalue(0))-32)* 5/9));
}
}
}
}
The above note:
[java] View Plain Text
/* XML reader XML reader = sax factory . newsaxparser()。 getxml reader(); //get XMLReader
XmlReader.setContentHandler (handler);
XML reader . parse(new input source(stream));
stream . close(); */
Is another way to parse with XMLReader. The effect is the same. You can pass a stream or a string here, as shown below: it is a string.
[java] View Plain Text
XML reader . parse(new input source(new string reader(XML str)));
Pull mode
In addition to SAX and DOM, you can also use the Pull parser built into Android to parse XML files. Pull parsers operate in a similar way to SAX parsers. It is also triggered by events. Pull parsing gives the application complete control over how the document is parsed. For example, start and end element events, use parser.next () to enter the next element and trigger the corresponding events. The code value of the event is obtained by the Parser.getEventType () method, and most of the processing is completed at the beginning of parsing. Events will be sent as digital codes, so you can use switches to handle events of interest.
Pull parsing is the process of traversing the document. Every time you call next (), nextTag (), nextToken () and nextText (), you will move the document forward and make the parser stay on some events, but you can't go back. Then set the document as a parser.
The API supporting the pull method in Android mainly includes
org.xmlpull.v 1。 XmlPullParser
org.xmlpull.v 1。 XmlPullParserFactory
Two classes, of which the main use is XmlPullParser, XmlPullParserFactory is a factory used to build XmlPullParser objects.
The application generates an event by calling methods such as XmlPullParser.next (), and then handles the event.
Let's take part of the XML file of the weather forecast above as an example.
For example, the XML file to be parsed is:
[java] View Plain Text
& lt Forecast _ Condition & gt
& lt what day of the week data= "Wednesday"/>
& lt●data = " 22 "/>
& lthigh data="29"/>
& lticon data = "/ig/images/weather/chance _ of _ rain . gif "/& gt;
& ltConditionaldata = "It may rain"/>
& lt/forecast _ conditions & gt;
In this part of XML file, day_of_week, low, high, etc. are tags, and data are attributes A a. Of course, if there are any.
To parse a document, you must first build an XmlPullParser object.
[java] View Plain Text
final XmlPullParserFactory factory = XmlPullParserFactory . new instance();
factory . setnamespace aware(true);
final XML pull parser parser = factory . newpullparser();
parser . set input(new string reader(" XML str ");
The xmlStr here is the XML file above.
At this time, the document has just been initialized, and it should be at the beginning of the document. The event is START_DOCUMENT, which can be obtained through XmlPullParser.getEventType (). Then calling next () will produce
START_TAG, this event tells the application that a tag has started, and calling getName () will return "day _ of _ week"; If there is text, next () will generate a text event and calling getText () will return the text. Since there is no text here, next () will generate END_TAG, telling you that a tag has been processed, and next () will generate END_DOCUMENT until the tag is finally processed, telling you that the whole document has been processed. In addition to next (), you can also use nextToken (), but it will return more detailed events, such as COMMENT, CDSECT, DOCDECL, ENTITY, and so on. If a program gets relatively low-level information, it can use nextToken () to drive and handle detailed events. It should be noted that text events may return white space, such as line breaks or spaces.
NextTag()-white space will be ignored. If you can determine whether the next one is START_TAG or END_TAG, you can call nextTag () to skip directly. There are usually two purposes: when using START_TAG, if it can be determined that this tag contains a subtag, then you can call nextTag () to generate the START_TAG event of the subtag; END_TAG, if it is determined that it is not the end of the document, you can call nextTag () to generate the START_TAG of the next tag. In both cases, if you use next (), there will be a text event, but a newline or white space character will be returned.
NextText()-can only be called at START_TAG. When the next element is text, the content of the text will be returned; When the next element is END_TAG, that is, the content of this tag is empty, then an empty string is returned; After the method returns, the parser will stop at END_TAG.
To sum up, if we only need the first part of data in an XML document, the whole document will be parsed by SAX or DOM, although we don't need to parse most of the data in the XML document, which is actually a waste of processing resources. The method of pulling is just right.
When you click any button in these three ways, you can get the same result.
- Previous article:What is the grammar of Chinese?
- Next article:The weather in Bei 'an today
- Related articles
- Introduction of Dalian North China Tourist Attractions Introduction of Dalian Tourist Attractions
- What is the city of Ganzhou like? What's the climate like? Is it hot in summer? How's the diet?
- Tanzhou weather query
- The Greek God Zeus (Jupiter)
- The weather forecast for tomorrow says it will rain, but how about organizing a trip to Jinjiang Paradise?
- Dreaming of the omen of Tathagata Bodhisattva
- Csol console command? Everyone!
- Will it snow during the Spring Festival of 20 19 in Jiangxi? Will it be cold in Jiangxi during the Spring Festival?
- What is the population of Hetang District, Zhuzhou City, Hunan Province?
- Write a diary of the first day of the scene in 300 words.