Parsing XML using SAX method

Source: Internet
Author: User

is divided into three parts:


1.

Package com;


Import java.io.IOException;


Import javax.xml.parsers.ParserConfigurationException;
Import Javax.xml.parsers.SAXParser;
Import Javax.xml.parsers.SAXParserFactory;


Import org.xml.sax.SAXException;


Import Com.ii.SAXParserHandler;
Import Com.jj.Book;


public class Saxtest {


public static void Main (string[] args) {
TODO auto-generated Method Stub

Get an instance of a saxparsefactory
SAXParserFactory factory = Saxparserfactory.newinstance ();

Get SAXParser through Factory
try {
SAXParser parser = Factory.newsaxparser ();

Create factory Get SAXParser instance
Saxparserhandler handler = new Saxparserhandler ();
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 | Saxexception e) {
TODO auto-generated Catch block
E.printstacktrace ();

} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}


}


}



2.

Package COM.II;


Import java.util.ArrayList;


Import javax.xml.stream.events.StartElement;


Import org.xml.sax.Attributes;
Import org.xml.sax.SAXException;
Import Org.xml.sax.helpers.DefaultHandler;


Import Com.jj.Book;


public class Saxparserhandler extends DefaultHandler {
String value = null;
Book book = null;
Private arraylist<book> Booklist = new arraylist<book> ();

Public arraylist<book> getbooklist () {
return Booklist;
}


int bookindex = 0;
/*
* Used to traverse the start tag of an XML file
* Used to parse XML elements.
* */
@Override
public void Startelement (string uri, String localname, String qName,
Attributes Attributes) throws Saxexception {
TODO auto-generated Method Stub

Call the Startelement () method of the DefaultHandler class;
Super.startelement (URI, LocalName, qName, attributes);
Begin parsing the properties of the book element

if (Qname.equals ("book")) {
Create a book Object
Book = new book ();


bookindex++;
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);
System.out.println ("===================== begins to traverse the" + Bookindex + "contents of this book =============================");
How to get property names and property values without knowing the name and number of attributes under the book element
int num = Attributes.getlength ();
for (int i = 0; i < num; i++) {

System.out.print ("book element:" + (i + 1) + "attribute name is:" + attributes.getqname (i));
SYSTEM.OUT.PRINTLN ("----attribute value is:" + attributes.getvalue (i));
if (Attributes.getqname (i). Equals ("id")) {
Book.setid (Attributes.getvalue (i));

}
}
}
else if (!qname.equals ("book") &&!qname.equals ("bookstore")) {
System.out.print ("Node name is:" + qName);

}
}

/*
* Used to identify the start of parsing
* */
@Override
public void Startdocument () throws Saxexception {
TODO auto-generated Method Stub
System.out.println ("Sax parsing begins!! ");
Super.startdocument ();
}

/*
* Used to identify the end of parsing
* */
@Override
public void Enddocument () throws Saxexception {
TODO auto-generated Method Stub
System.out.println ("Sax parsing is over!! ");
Super.enddocument ();
}
/*
* Used to traverse the end tag of an XML file
* */
@Override
public void EndElement (string uri, String localname, String qName)
Throws Saxexception {
TODO auto-generated Method Stub
Super.endelement (URI, LocalName, QName);
if (Qname.equals ("book")) {
Booklist.add (book);
book = null;
System.out.println ("===================== End Traversal" + Bookindex + "contents of this 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 void characters (char[] ch, int start, int length)
Throws Saxexception {
TODO auto-generated Method Stub
Super.characters (CH, start, length);

Value = new String (CH, start, length);
if (!value.trim (). Equals ("")) {
System.out.println ("--node value is:" + value);
}


}
}



3.


Package COM.JJ;


public class Book {
Private String ID;
private String name;
Private String author;
Private String year;
Private String Price;
Private String language;


Public String getId () {
return ID;
}
public void SetId (String id) {
This.id = ID;
}
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
Public String Getauthor () {
return author;
}
public void Setauthor (String author) {
This.author = author;
}
Public String GetYear () {
Return year;
}
public void Setyear (String year) {
This.year = year;
}
Public String GetPrice () {
return price;
}
public void Setprice (String price) {
This.price = Price;
}
Public String GetLanguage () {
return language;
}
public void SetLanguage (String language) {
This.language = language;
}

}

Parsing XML using SAX method

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.