Android Simple XML parsing

Source: Internet
Author: User

Create a Assets folder in Android project first App/src/main/assets

Add a file named Data.xml here and edit the file to include the following XML format:

<?XML version= "1.0" encoding= "Utf-8"?><Apps>    <app>        <ID>1</ID>        <name>Google Maps</name>        <version>1.0</version>    </app>    <app>        <ID>2</ID>        <name>Chrome</name>        <version>2.1</version>    </app>    <app>        <ID>3</ID>        <name>Google Play</name>        <version>2.3</version>    </app></Apps>

============== get the content in XML ================

@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Try {            //gets the input stream of the XML fileInputStream FIS = getresources (). Getassets (). Open ("Data.xml"); InputStreamReader ISR=NewInputStreamReader (FIS, "UTF-8"); StringBuffer StringBuffer=NewStringBuffer (); intMark =-1;  while(Mark = Isr.read ())! =-1) {stringbuffer.append (Char) mark); } String Data=stringbuffer.tostring (); //to pass the entire file content as a string//parsexmlwithpull (data); //parsexmlwithsax (data);        } Catch(IOException e) {e.printstacktrace (); }    }

==============pull parsing mode =================

Get Parse tool Xmlpullparser:
Xmlpullparserfactory factory = Xmlpullparserfactory.newinstance ();
Xmlpullparser Xmlpullparser = Factory.newpullparser ();

Incoming XML character stream:
Xmlpullparser.setinput (new StringReader (XmlData));

Processing according to the node characteristics:
Switch (Xmlpullparser.geteventtype ())

    Private voidparsexmlwithpull (String xmlData) {Try{xmlpullparserfactory Factory=xmlpullparserfactory.newinstance (); Xmlpullparser Xmlpullparser=Factory.newpullparser (); Xmlpullparser.setinput (NewStringReader (xmlData)); intEventType =Xmlpullparser.geteventtype (); String ID= ""; String name= ""; String version= "";  while(EventType! =xmlpullparser.end_document) {String NodeName=Xmlpullparser.getname (); Switch(eventtype) {//start parsing a node                     CaseXmlpullparser.start_tag: {if("id". Equals (NodeName)) {ID=Xmlpullparser.nexttext (); } Else if("Name". Equals (NodeName)) {Name=Xmlpullparser.nexttext (); } Else if("Version". Equals (NodeName)) {Version=Xmlpullparser.nexttext (); }                    }                     Break; //finish parsing a node                     CaseXmlpullparser.end_tag: {if("App". Equals (NodeName)) {LOG.D ("Woider", "ID is" +ID); LOG.D ("Woider", "name is" +name); LOG.D ("Woider", "version is" +version); }                    }                     Break; } EventType=Xmlpullparser.next (); }        } Catch(Exception e) {e.printstacktrace (); }    }
Parsexmlwithpull

==============sax parsing mode =================

Using sax parsing typically requires creating a class that inherits DefaultHandler and overrides the five methods of the parent class

Startdocument (): Called when XML parsing is started
Startelement (): Called when parsing a node is started
Characters (): Gets the contents of the node when called
EndElement (): Called when parsing a node is complete
Enddocument (): Called when the entire XML parsing is complete

 Public classContentHandlerextendsDefaultHandler {PrivateString NodeName; PrivateStringBuilder ID; PrivateStringBuilder name; PrivateStringBuilder version; @Override Public voidStartdocument ()throwssaxexception {ID=NewStringBuilder (); Name=NewStringBuilder (); Version=NewStringBuilder (); } @Override Public voidstartelement (String uri, String localname, String qName, Attributes Attributes)throwssaxexception {//remember the current node nameNodeName =LocalName; } @Override Public voidCharacters (Char[] ch,intStartintLengththrowssaxexception {//to format normalizationString str =NewString (CH, start, length). Trim (); //add content based on the current node name        if("id". Equals (NodeName))        {id.append (str); } Else if("Name". Equals (NodeName))        {name.append (str); } Else if("Version". Equals (NodeName))        {version.append (str); }} @Override Public voidEndElement (String uri, String localname, String qName)throwssaxexception {if("App". Equals (LocalName)) {LOG.D ("Woider", "ID is" +ID); LOG.D ("Woider", "name is" +name); LOG.D ("Woider", "version is" +version); //empty StringBuilderId.setlength (0); Name.setlength (0); Version.setlength (0); }} @Override Public voidEnddocument ()throwssaxexception {}}
ContentHandler

Get Parse tool XmlReader:
SAXParserFactory factory = Saxparserfactory.newinstance ();
XMLReader XMLReader = Factory.newsaxparser (). Getxmlreader ();

Incoming rule to parse tool:
ContentHandler handler = new ContentHandler ();
Xmlreader.setcontenthandler (handler);

To begin the parse execution:
Xmlreader.parse (New InputSource (new StringReader (XmlData)));

    Private voidParsexmlwithsax (String xmlData) {Try{SAXParserFactory Factory=saxparserfactory.newinstance (); XMLReader XMLReader=Factory.newsaxparser (). Getxmlreader (); ContentHandler Handler=NewContentHandler (); //to set an instance of ContentHandler to XmlReaderXmlreader.setcontenthandler (handler); //Start Execution parsingXmlreader.parse (NewInputSource (NewStringReader (xmlData)); } Catch(Exception e) {e.printstacktrace (); }    }
Parsexmlwithsax

Method Two (directly for InputStream parsing)

Get Parse tool SAXParser:
SAXParserFactory factory = Saxparserfactory.newinstance ();
SAXParser parser = Factory.newsaxparser ();

Get rules and input streams:
Handler = new Parserhandler ();
InputStream InputStream = Getresources (). Getassets (). Open ("Data.xml");

Simultaneous incoming start parsing:
Parser.parse (InputStream, handler);

Finally print the LogCat in the log, data.xml resolution is completed

In addition to pull parsing and SAX parsing, there is also a DOM parsing that is important.

There are also XML parsing tools, such as JDOM and dom4j, that simplify the parsing process and improve the efficiency of parsing.

Android Simple XML parsing

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.