Using xml as a carrier for data interaction is a very important feature in Android. for example, weather forecast data, text message backup data, and messaging data can all be stored in xml
1. Generate and parse data in Xml format
Using xml as a carrier for data interaction is a very important feature in Android. for example, weather forecast data, text message backup data, and messaging data can all be stored in xml
The format is transmitted over the network.
The XML format is clearly written and displayed in the form of notes for easy reading and recognition, as shown below:
Zhang San
110001
Male
XML generation
If you use java code to implement such a string format, you can use StringBuilder for grouping: StringBuilder sb = new StringBuilder ();
// Save the data to the file sb. append ("
"); Sb. append ("
"); Sb. append ("
"); Sb. append (name); sb. append ("
"); Sb. append ("
"); Sb. append (number); sb. append ("
"); Sb. append ("
"); Sb. append (sex); sb. append ("
"); Sb. append ("
");
The above code can also generate xml
File, but cannot process special characters. for example, if the text message content contains the "" symbol
The parser cannot complete the correct parsing. Therefore, you must ensure that the data content does not contain any special characters.
Android provides an API specifically used to generate XML data: XmlSerializer.
The code for handling special characters is as follows:
Try {// generate xml file using Android api object-oriented. // 1. get the XmlSerializer serializer = xml. newSerializer (); // 2. specify some initial parameters File = new file (getFilesDir (), name + ". xml "); FileOutputStream OS = new FileOutputStream (file); serializer. setOutput (OS, "UTF-8"); // 3. write an xml file. serializer. startDocument ("UTF-8", true); // starts with serializer. startTag (null, "student"); // Start label serializer. startTag (null, "name"); serializer. text (name); // text label serializer. endTag (null, "name"); // end label serializer. startTag (null, "number"); serializer. text (number); serializer. endTag (null, "number"); serializer. startTag (null, "sex"); serializer. text (sex); serializer. endTag (null, "sex"); serializer. endTag (null, "student"); serializer. endDocument (); // write the end OS. close (); Toast. makeText (this, "data saved successfully", 0 ). show ();} catch (Exception e) {e. printStackTrace (); Toast. makeText (this, "failed to save data", 0 ). show ();}
XML parsing
1. DOM parsing
Is an object-based API that stores all the content of an XML file in the memory as a document tree, and then allows the use of DOMAPI to traverse the XML tree and retrieve the required data, in this way, files can be operated in the form of nodes based on the tree structure. Because DOM needs to store the entire XML file in the memory in the form of a document tree, which consumes a large amount of memory, I don't mind using this method for parsing in Android.
2. SAX parsing
XML documents are scanned row by row. when tags are encountered, the parsing processor is triggered and XML is parsed by event processing. It can process XML while reading the document. it does not have to wait until the document loading is complete, it is relatively fast, and it does not need to load the entire document into the memory. Therefore, there is no memory occupation problem, large XML can be parsed. However, SAX parsing can only be used to read XML data and cannot be added, deleted, or modified.
3. PULL parsing is similar to SAX parsing and is also based on event processing. The PULL parser is an open-source Java project that can be used for both Android applications and Java EE programs. Android has integrated the PULL parser. Therefore, the most common parsing method in android is PULL parsing.
Comparison between SAX and PULL parsing: The Running mode of the Pull parser and the SAX
The parser is similar and belongs to the event-driven mode. It provides similar events, such as the start element and end element events. you can use parser. next () to enter the next element and trigger the corresponding event. The event is sent as a numeric code, so you can use a switch
Process events of interest. When parsing an element, call parser. nextText () to obtain the next Text
The value of the type element.
The SAX parser automatically pushes events to the event processor for processing. Therefore, you cannot control the event processing to automatically end.
The parser works in a way that allows your application code to actively retrieve events from the parser. because it is actively obtaining events, you can stop obtaining events after meeting the required conditions, end parsing.
The code for parsing XML files using PULL in Android is as follows:
Try {// The xml file of student information exists // 1. get an xml parser XmlPullParser parser = Xml. newPullParser (); // 2. set the parser's initialization parameter FileInputStream inputStream = new FileInputStream (file); parser. setInput (inputStream, "UTF-8"); // 3. parse the xml file int type = parser. getEventType (); // obtain the type of the first event. system. out. println ("type:" + type); StringBuilder sb = new StringBuilder (); // when the event type is not the end of the document, it will always traverse each node while (type! = XmlPullParser. END_DOCUMENT) {if (type = XmlPullParser. START_TAG) {// start node // judge the node name if ("name ". equals (parser. getName () {String nameStr = parser. nextText (); System. out. println ("name:" + nameStr); sb. append ("name:" + nameStr + "\ n");} else if ("number ". equals (parser. getName () {String numberStr = parser. nextText (); System. out. println ("student ID:" + numberStr); sb. append ("student ID:" + numberStr + "\ n");} else if ("sex ". equals (parser. getName ())) {String sexStr = parser. nextText (); System. out. println ("Gender:" + sexStr); sb. append ("Gender:" + sexStr + "\ n") ;}} type = parser. next (); // Obtain the next event type System. out. println ("type:" + type);} inputStream. close (); // memory leakage caused by resource waste! TV _result.setText (sb. toString ();} catch (Exception e) {e. printStackTrace (); Toast. makeText (this, "Failed to parse student information", 0 ). show ();}
The above is the details of the code for generating and parsing Xml format data. For more information, see other related articles in the first PHP community!