Sax parsing xml

Source: Internet
Author: User

Resolution steps:

1. Get saxparserfactory instance by saxparserfactory static newinstance () method factory

2. Return the SAXParser instance through the Newsaxparser () method of the SAXParserFactory instance parser

3. Create a class to inherit DefaultHandler, override some of these methods for business processing and create an instance of this class handler

XML file that needs parsing book.xml

<?XML version= "1.0" encoding= "UTF-8"?><Bookstore>    < BookID= "1">        <name>The song of Ice and Fire</name>        <author>George Martin</author>        < Year>2014</ Year>        < Price>89</ Price>    </ Book>    < BookID= "2">        <name>Andersen Fairy Tale</name>        < Year>2004</ Year>        < Price>77</ Price>        <language>中文版</language>    </ Book>    </Bookstore>

Book.java

 Packagecom.imooc.entity; Public classBook {PrivateString ID; PrivateString name; PrivateString author; PrivateString Year; PrivateString Price; PrivateString language;  PublicString getId () {returnID; }     Public voidsetId (String id) { This. ID =ID; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicString Getauthor () {returnauthor; }     Public voidSetauthor (String author) { This. Author =author; }     PublicString getYear () {returnYear ; }     Public voidSetyear (String year) { This. Year =Year ; }     PublicString GetPrice () {returnPrice ; }     Public voidSetprice (String price) { This. Price =Price ; }     PublicString GetLanguage () {returnlanguage; }     Public voidSetLanguage (String language) { This. Language =language; }        }

Saxparserhandler.java

 PackageCom.imooc.handler;Importjava.util.ArrayList;Importorg.xml.sax.Attributes;Importorg.xml.sax.SAXException;ImportOrg.xml.sax.helpers.DefaultHandler;ImportCom.imooc.entity.Book; Public classSaxparserhandlerextendsDefaultHandler {String value=NULL; Book Book=NULL; PrivateArraylist<book> Booklist =NewArraylist<book>();  PublicArraylist<book>getbooklist () {returnBooklist; }    intBookindex = 0; /*** Used to identify the start of parsing*/@Override Public voidStartdocument ()throwssaxexception {//TODO auto-generated Method Stub        Super. Startdocument (); System.out.println ("Sax parsing begins"); }        /*** Used to identify the end of parsing*/@Override Public voidEnddocument ()throwssaxexception {//TODO auto-generated Method Stub        Super. Enddocument (); System.out.println ("Sax parsing Ends"); }        /*** Parsing XML elements*/@Override Public voidstartelement (String uri, String localname, String qName, Attributes Attributes)throwssaxexception {//call the Startelement method of the DefaultHandler class        Super. Startelement (URI, LocalName, qName, attributes); if(Qname.equals ("book") ) {Bookindex++; //Create a book objectBook =NewBook (); //begin parsing the properties of the book elementSystem.out.println ("====================== begins to traverse the contents of a book =================");//            //The name of the property under the known book element, which gets the property value based on the property name//String value = attributes.getvalue ("id");//System.out.println ("book's Attribute value is:" + value); //do not know the name and number of attributes under the book element, how to get the property name and the property value            intnum =attributes.getlength ();  for(inti = 0; i < num; i++) {System.out.print ("The book Element's" + (i + 1) + "property name is:" +Attributes.getqname (i)); System.out.println (The---property value is: "+Attributes.getvalue (i)); if(Attributes.getqname (i). Equals ("id") {Book.setid (Attributes.getvalue (i)); }            }        }        Else if(!qname.equals ("name") &&!qname.equals ("bookstore") {System.out.print ("Node name is:" + qName + "---"); }} @Override Public voidendElement (String uri, String localname, string qName)throwssaxexception {//call the EndElement method of the DefaultHandler class        Super. EndElement (URI, LocalName, QName); //Judging whether a book has been traversed to the end        if(Qname.equals ("book") {booklist.add (book); Book=NULL; System.out.println ("====================== ends the traversal of the contents of a book ================="); }        Else if(Qname.equals ("name") {book.setname (value); }        Else if(Qname.equals ("Author") {book.setauthor (value); }        Else if(Qname.equals ("Year") {book.setyear (value); }        Else if(Qname.equals ("Price") {book.setprice (value); }        Else if(Qname.equals ("language") {book.setlanguage (value); }} @Override Public voidCharacters (Char[] ch,intStartintlength)throwssaxexception {        Super. Characters (ch, start, length); Value=NewString (CH, start, length); if(!value.trim (). Equals ("") {System.out.println ("Node value is:" +value); }    }}

Saxtext.java

 Packagecom.imooc.test;Importjava.io.IOException;Importjavax.xml.parsers.ParserConfigurationException;ImportJavax.xml.parsers.SAXParser;Importjavax.xml.parsers.SAXParserFactory;Importorg.xml.sax.SAXException;Importorg.xml.sax.SAXParseException;ImportCom.imooc.entity.Book;ImportCom.imooc.handler.SAXParserHandler; Public classSaxtest {/**     * @paramargs*/     Public Static voidMain (string[] args) {//Get aSAXParserFactory InstancesSAXParserFactory factory =saxparserfactory.newinstance (); //ThroughFactory getting SAXParser instances        Try{saxparser parser=Factory.newsaxparser (); //CreateSaxparserhandler ObjectSaxparserhandler handler =NewSaxparserhandler (); Parser.parse ("Books.xml", Handler); System.out.println ("~ ~ ! ! Total "+handler.getbooklist (). Size ()+ "book");  for(book Book:handler.getBookList ()) {System.out.println (Book.getid ());                System.out.println (Book.getname ());                System.out.println (Book.getauthor ());                System.out.println (Book.getyear ());                System.out.println (Book.getprice ());                System.out.println (Book.getlanguage ()); System.out.println ("----Finish----"); }        } Catch(parserconfigurationexception e) {E.printstacktrace (); } Catch(saxexception e) {E.printstacktrace (); } Catch(IOException e) {E.printstacktrace (); }    }}

Sax parsing xml

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.