Android (java) Learning Note 106:android XML parsing

Source: Internet
Author: User
Tags closing tag ming tagname xml parser
<span id="Label3"></p><p><p>The XML file can be parsed on the Android platform using the simple API for XML (SAX), the document Object Model (DOM), and the pull parser included with Android.</p></p><p><p></p></p><p><p>Here is the XML file to parse for this example:</p></p><p><p>File Name: Itcast.xml</p></p><p><p><?xml version= "1.0" encoding= "UTF-8"?></p></p><p><p><persons></p></p><p><p><person id= ">"</p></p><p><p><name> Li Ming </name></p></p><p><p><age>30</age></p></p><p><p></person></p></p><p><p><person id= ">"</p></p><p><p><name> Li Xiangmei </name></p></p><p><p><age>25</age></p></p><p><p></person></p></p><p><p></persons></p></p><p><p>The example defines a javabean for storing the XML content parsed above, The JavaBean is the person, the Code:</p></p><p><p>public class Person {</p></p><p><p>Private Integer id;</p></p><p><p>Private String name;</p></p><p><p>Private short age;</p></p><p><p>Public Integer getId () {</p></p><p><p>Return id;</p></p><p><p>}</p></p><p><p>public void SetId (Integer Id) {</p></p><p><p>This.id = id;</p></p><p><p>}</p></p><p><p>Public String getName () {</p></p><p><p>Return name;</p></p><p><p>}</p></p><p><p>public void SetName (String Name) {</p></p><p><p>THIS.name = name;</p></p><p><p>}</p></p><p><p>Public short Getage () {</p></p><p><p>Return age;</p></p><p><p>}</p></p><p><p>public void Setage (short Age) {</p></p><p><p>This.age = age;</p></p><p><p>}</p></p><p><p>}</p></p><p><p><strong>To read an XML file using sax</strong></p></p><p><p>Sax is a fast parsing and memory-intensive XML parser that is ideal for mobile devices such as Android. the <strong>Sax Parsing xml file is event-driven, that is, it does not need to parse the entire document, and in the process of parsing the document in order of content, sax determines whether the currently read character is a part of the valid XML syntax, and triggers the event if it conforms. The so-called events are actually some callback (callback) methods, which are defined in the ContentHandler interface. </strong></p></p><p><p>Here are some common methods for ContentHandler interfaces:</p></p> <ul> <ul> <li> <strong> startdocument ()    </strong> When you encounter the beginning of the document, call this method, where you can do some preprocessing Work. </li> <li> <strong> enddocument ()      </strong> corresponds to the method above, and when the document is finished, it is called to do some aftercare Work.   </li> <li> <strong> startelement (string namespaceuri, string localname, string qName, Attributes atts)       </strong> This method is triggered when a start tag is Read. NamespaceURI is a namespace, localname is a label name without a namespace prefix, and QName is a label name with a namespace prefix. All property names and corresponding values can be obtained by atts. Note that one of the important features of Sax is its streaming, when it encounters a tag, it does not record the tags that were encountered before, that is, in the startelement () method, all the information you know is the name and attributes of the tag, as for the nested structure of the tag, The name of the upper label, whether there is a sub-genus and other information related to the structure, are not known, all need your program to Complete. This makes sax less convenient for programming without DOM. </li> <li> <strong> endElement (string uri, string localname, string Name)     </strong> This method corresponds to the above methods, This method is called when the closing tag is Encountered. </li> <li> <strong> characters (char[] ch, int start, int Length)      </strong> This method is used to handle what is read in the XML file. The first parameter is used to hold the contents of the file, and the next two parameters are the starting position and length of the string to be read in the array, and the content can be obtained using new string (ch,start,length). </li> </ul> </ul><p><p><strong>The events triggered by parsing Itcast.xml are:</strong></p></p><p><p>Read tags and content triggering events</p></p><p><p>{document start} startdocument ()</p></p><p><p><persons> startelement (, "persons", null, "{Attributes}")</p></p><p><p>"\n\t" characters ("<persons>...</persons>", "12", "2")</p></p><p><p><person> startelement (, "person", null, "{Attributes}")</p></p><p><p>"\n\t\t" characters ("<persons>...</persons>", "31", "3")</p></p><p><p><name> startelement (, "name", null, "{Attributes}")</p></p><p><p>"li ming" characters ("<persons>...</persons>", "40", "2")</p></p><p><p></name> endElement ("", "name", Null)</p></p><p><p>"\n\t\t" characters ("<persons>...</persons>", "50", "3")</p></p><p><p><age> startelement (, "age", null, "{Attributes}")</p></p><p><p>"characters" ("<persons>...</persons>", "58", "2")</p></p><p><p></age> endElement ("", "age", Null)</p></p><p><p>"\n\t" characters ("<persons>...</persons>", "67", "2")</p></p><p><p></person> endElement ("", "person", Null)</p></p><p><p>"\n\t" characters ("<persons>...</persons>", "79", "2")</p></p><p><p><person> startelement (, "person", null, "{Attributes}")</p></p><p><p>"\n\t\t" characters ("<persons>...</persons>", "98", "3")</p></p><p><p><name> startelement (, "name", null, "{Attributes}")</p></p><p><p>"Li Xiangmei" characters ("<persons>...</persons>", "107", "3")</p></p><p><p></name> endElement ("", "name", Null)</p></p><p><p>"\n\t\t" characters ("<persons>...</persons>", "118", "3")</p></p><p><p><age> startelement (, "age", null, "{Attributes}")</p></p><p><p>"characters" ("<persons>...</persons>", "126", "2")</p></p><p><p></age> endElement ("", "age", Null)</p></p><p><p>"\n\t" characters ("<persons>...</persons>", "135", "2")</p></p><p><p></person> endElement ("", "person", Null)</p></p><p><p>"\ n" characters ("<persons>...</persons>", "147", "1")</p></p><p><p></persons> endElement ("", "persons", Null)</p></p><p><p>{document end} enddocument ()</p></p><p><p>Whenever a class that implements the ContentHandler interface is provided for sax, the class can get a notification event (in effect, Sax calls the callback method in the Class). <strong>because ContentHandler is an interface that may be inconvenient when used, sax also has a helper class for It: defaulthandler, which implements this interface, but all of its method bodies are empty, and when implemented, You only need to inherit this class and then overload the appropriate method</strong> . The code for parsing itcast.xml using sax is as Follows:</p></p><p><p>public static list<person> ReadXML (inputstream Instream) {</p></p><p><p>try {</p></p><p><p>SAXParserFactory SPF = saxparserfactory.newinstance ();</p></p><p><p>SAXParser SAXParser = Spf.newsaxparser (); Creating a parser</p></p><p><p>Sets the correlation attribute of the parser, http://xml.org/sax/features/namespaces = True to open the namespace attribute</p></p><p><p>Saxparser.setproperty ("http://xml.org/sax/features/namespaces", true);</p></p><p><p>Xmlcontenthandler handler = new Xmlcontenthandler ();</p></p><p><p>Saxparser.parse (instream, handler);</p></p><p><p>Instream.close ();</p></p><p><p>return handler.getpersons ();</p></p><p><p>} catch (Exception E) {</p></p><p><p>E.printstacktrace ();</p></p><p><p>}</p></p><p><p>Return null;</p></p><p><p>}</p></p><p><p>Import java.util.ArrayList;</p></p><p><p>Import java.util.List;</p></p><p><p>Import org.xml.sax.Attributes;</p></p><p><p>Import org.xml.sax.SAXException;</p></p><p><p>Import org.xml.sax.helpers.DefaultHandler;</p></p><p><p>Import cn.itcast.xml.domain.Person;</p></p><p><p>public class Xmlcontenthandler extends DefaultHandler {</p></p><p><p>Private list<person> persons = null;</p></p><p><p>Private person currentperson;</p></p><p><p>Private String TagName = null;//the element label that is currently parsed</p></p><p><p>Public list<person> getpersons () {</p></p><p><p>Return persons;</p></p><p><p>}</p></p><p><p>/*</p></p><p><p>* Receive notification of the beginning of the Document.</p></p><p><p>*/</p></p><p><p>@Override public void Startdocument () throws saxexception {</p></p><p><p>persons = new Arraylist<person> ();</p></p><p><p>}</p></p><p><p>/*</p></p><p><p>* Receive notification of character Data.</p></p><p><p>*/</p></p><p><p>@Override public void characters (char[] ch, int start, int Length) throws Saxexception {</p></p><p><p>If (tagname!=null) {</p></p><p><p>String data = new String (ch, start, length);</p></p><p><p>If (tagname.equals ("name")) {</p></p><p><p>This.currentPerson.setName (data);</p></p><p><p>}else if (tagname.equals ("age")) {</p></p><p><p>This.currentPerson.setAge (short.parseshort (data));</p></p><p><p>}</p></p><p><p>}</p></p><p><p>}</p></p><p><p>/*</p></p><p><p>* Receive notification of the start of the Element.</p></p><p><p>* parameter meaning is as Follows:</p></p><p><p>* Namespaceuri: Element namespace</p></p><p><p>* Localname: local name of element (without Prefix)</p></p><p><p>* QName: the qualified name of the element (prefixed)</p></p><p><p>* Atts: attribute collection of elements</p></p><p><p>*/</p></p><p><p>@Override public void startelement (string namespaceuri, string localname, string qName, Attributes Atts) throws Saxexcepti on {</p></p><p><p>If (localname.equals ("person")) {</p></p><p><p>Currentperson = new Person ();</p></p><p><p>Currentperson.setid (integer.parseint (atts.getvalue ("id")));</p></p><p><p>}</p></p><p><p>This.tagname = localname;</p></p><p><p>}</p></p><p><p>/*</p></p><p><p>* Receive notifications at the end of the Document.</p></p><p><p>* parameter meaning is as Follows:</p></p><p><p>* Uri: namespace of the element</p></p><p><p>* Localname: local name of element (without Prefix)</p></p><p><p>* Name: the qualified name of the element (prefixed)</p></p><p><p>*</p></p><p><p>*/</p></p><p><p>@Override public void EndElement (string uri, string localname, string Name) throws Saxexception {</p></p><p><p>If (localname.equals ("person")) {</p></p><p><p>Persons.add (currentperson);</p></p><p><p>Currentperson = null;</p></p><p><p>}</p></p><p><p>This.tagname = null;</p></p><p><p>}</p></p><p><p>}</p></p><p><p><strong>Reading an XML file using the DOM</strong></p></p><p><p>In addition to using SAX to parse XML files, You can also use the familiar DOM to parse XML files. When the DOM parses an XML file, it reads all the contents of the XML file into memory, and then allows you to use the DOM API to traverse the XML tree and retrieve the data you Need. The code that uses the DOM to manipulate XML looks more intuitive and, in some ways, simpler than sax-based Implementations. however, because the DOM needs to read all the contents of the XML file into memory, so the memory consumption is large, especially for mobile devices running android, because the resources of the device is more valuable, so it is recommended to use Sax to parse the XML file, of course, It is possible to use the DOM if the content of the XML file is relatively small.</p></p><p><p>Import java.io.InputStream;</p></p><p><p>Import java.util.ArrayList;</p></p><p><p>Import java.util.List;</p></p><p><p>Import javax.xml.parsers.DocumentBuilder;</p></p><p><p>Import javax.xml.parsers.DocumentBuilderFactory;</p></p><p><p>Import org.w3c.dom.Document;</p></p><p><p>Import org.w3c.dom.Element;</p></p><p><p>Import org.w3c.dom.Node;</p></p><p><p>Import org.w3c.dom.NodeList;</p></p><p><p>Import cn.itcast.xml.domain.Person;</p></p><p><p>/**</p></p><p><p>* Parsing XML files using DOM</p></p><p><p>*</p></p><p><p>*/</p></p><p><p>public class Domxmlreader {</p></p><p><p>public static list<person> ReadXML (inputstream Instream) {</p></p><p><p>list<person> persons = new Arraylist<person> ();</p></p><p><p>Documentbuilderfactory factory = Documentbuilderfactory.newinstance ();</p></p><p><p>try {</p></p><p><p>Documentbuilder builder = Factory.newdocumentbuilder ();</p></p><p><p>Document dom = Builder.parse (instream);</p></p><p><p>Element root = dom.getdocumentelement ();</p></p><p><p>NodeList items = root.getelementsbytagname ("person");//find all person nodes</p></p><p><p>for (int i = 0; i < items.getlength (); I++) {</p></p><p><p>person person = new Person ();</p></p><p><p>Get the first person node</p></p><p><p>Element personnode = (element) Items.item (i);</p></p><p><p>Gets the ID property value of the person node</p></p><p><p>Person.setid (new Integer (personnode.getattribute ("id")));</p></p><p><p>Get all child nodes under the person node (white space nodes and name/age elements between Labels)</p></p><p><p>NodeList childsnodes = Personnode.getchildnodes ();</p></p><p><p>for (int j = 0; J < childsnodes.getlength (); J + +) {</p></p><p><p>Node node = (node) Childsnodes.item (j); Determine if the element type</p></p><p><p>If (node.getnodetype () = = Node.element_node) {element Childnode = (element) node;</p></p><p><p>Determine if the name element</p></p><p><p>If ("name". equals (childnode.getnodename ())) {</p></p><p><p>Gets the name element under the text node, and then gets the data from the text node</p></p><p><p>Person.setname (childnode.getfirstchild (). Getnodevalue ());</p></p><p><p>} else if ("age". equals (childnode.getnodename ())) {</p></p><p><p>Person.setage (new Short (childnode.getfirstchild (). getnodevalue ()));</p></p><p><p>}</p></p><p><p>}</p></p><p><p>}</p></p><p><p>Persons.add (person);</p></p><p><p>}</p></p><p><p>Instream.close ();</p></p><p><p>} catch (Exception E) {</p></p><p><p>E.printstacktrace ();</p></p><p><p>}</p></p><p><p>Return persons;</p></p><p><p>}</p></p><p><p><strong>To read an XML file using the Pull parser</strong></p></p><p><p>In addition to parsing XML files using sax and dom, You can also parse an XML file using the built-in pull parser from Android. <strong>The Pull parser operates in a similar way to the SAX parser. It provides similar events such as starting and ending element events, using Parser.next () to move to the next element and triggering the corresponding Event. Events are sent as numeric codes, so you can use a switch to handle the events of Interest. When the element begins parsing, the Parser.nexttext () method is called to get the value of the next text type Element. </strong></p></p><p><p>Pull parser source code and documentation download Url: http://www.xmlpull.org/</p></p><p><p>Import org.xmlpull.v1.XmlPullParser;</p></p><p><p>Import android.util.Xml;</p></p><p><p>Import cn.itcast.xml.domain.Person;</p></p><p><p>public class Pullxmlreader {</p></p><p><p>public static list<person> ReadXML (inputstream Instream) {</p></p><p><p>Xmlpullparser parser = Xml.newpullparser ();</p></p><p><p>try {</p></p><p><p>Parser.setinput (instream, "UTF-8");</p></p><p><p>int eventtype = Parser.geteventtype ();</p></p><p><p>Person Currentperson = null;</p></p><p><p>list<person> persons = null;</p></p><p><p>While (eventtype! = Xmlpullparser.end_document) {</p></p><p><p>Switch (eventtype) {</p></p><p><p>Case Xmlpullparser.start_document://document Start event, data initialization can be processed</p></p><p><p>persons = new Arraylist<person> ();</p></p><p><p>Break</p></p><p><p>Case Xmlpullparser.start_tag://start Element Event</p></p><p><p>String name = Parser.getname ();</p></p><p><p>If (name.equalsignorecase ("person")) {</p></p><p><p>Currentperson = new Person ();</p></p><p><p>Currentperson.setid (new Integer (parser.getattributevalue (null, "id"));</p></p><p><p>} else If (currentperson! = null) {</p></p><p><p>If (name.equalsignorecase ("name")) {</p></p><p><p>Currentperson.setname (parser.nexttext ());//if The text element is followed, it returns its value</p></p><p><p>} else if (name.equalsignorecase ("age")) {</p></p><p><p>Currentperson.setage (new Short (parser.nexttext ()));</p></p><p><p>}</p></p><p><p>}</p></p><p><p>Break</p></p><p><p>Case Xmlpullparser.end_tag://end Element Event</p></p><p><p>If (parser.getname (). equalsignorecase ("person") && currentperson! = null) {</p></p><p><p>Persons.add (currentperson);</p></p><p><p>Currentperson = null;</p></p><p><p>}</p></p><p><p>Break</p></p><p><p>}</p></p><p><p>EventType = Parser.next ();</p></p><p><p>}</p></p><p><p>Instream.close ();</p></p><p><p>Return persons;</p></p><p><p>} catch (Exception E) {</p></p><p><p>E.printstacktrace ();</p></p><p><p>}</p></p><p><p>Return null;</p></p><p><p>}</p></p><p><p>}</p></p><p><p><strong>Generating an XML file using the Pull parser</strong></p></p><p><p>sometimes, we need to generate an XML file, <strong>There are many ways to generate an XML file, such as: you can use only one StringBuilder group to spell XML content, and then write the content to a file, or use the DOM API to generate an XML file, alternatively, You can use the pull parser to generate an XML file, which we recommend using the pull Parser. </strong></p></p><p><p>Use the pull parser to generate a myitcast.xml file with the same contents as the Itcast.xml file.</p></p><p><p>public static String WriteXML (list<person> persons, writer Writer) {</p></p><p><p>XmlSerializer serializer = Xml.newserializer ();</p></p><p><p>try {</p></p><p><p>Serializer.setoutput (writer);</p></p><p><p>Serializer.startdocument ("UTF-8", true);</p></p><p><p>The first parameter is a namespace and can be set to NULL if you do not use a namespace</p></p><p><p>Serializer.starttag ("", "persons");</p></p><p><p>For (person Person:persons) {</p></p><p><p>Serializer.starttag ("", "person");</p></p><p><p>Serializer.attribute ("", "id", person.getid (). toString ());</p></p><p><p>Serializer.starttag ("", "name");</p></p><p><p>Serializer.text (person.getname ());</p></p><p><p>Serializer.endtag ("", "name");</p></p><p><p>Serializer.starttag ("", "age");</p></p><p><p>Serializer.text (person.getage (). toString ());</p></p><p><p>Serializer.endtag ("", "age");</p></p><p><p>Serializer.endtag ("", "person");</p></p><p><p>}</p></p><p><p>Serializer.endtag ("", "persons");</p></p><p><p>Serializer.enddocument ();</p></p><p><p>return writer.tostring ();</p></p><p><p>} catch (Exception E) {</p></p><p><p>E.printstacktrace ();</p></p><p><p>}</p></p><p><p>Return null;</p></p><p><p>}</p></p><p><p>Use the following code (to generate an XML file):</p></p><p><p>File XMLFile = new file ("myitcast.xml");</p></p><p><p>FileOutputStream OutStream = new FileOutputStream (xmlfile);</p></p><p><p>OutputStreamWriter outstreamwriter = new OutputStreamWriter (outstream, "UTF-8");</p></p><p><p>BufferedWriter writer = new BufferedWriter (outstreamwriter);</p></p><p><p>WriteXML (persons, writer);</p></p><p><p>Writer.flush ();</p></p><p><p>Writer.close ();</p></p><p><p>If you want to get only the generated XML content, you can use Stringwriter:</p></p><p><p>StringWriter writer = new StringWriter ();</p></p><p><p>WriteXML (persons, writer);</p></p><p><p>String content = writer.tostring ();</p></p><p><p>Android (java) Learning Note 106:android XML parsing</p></p></span>
Related Article

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.