Sax deepens the case, further through the case to explain SAX usage, this case includes explaining how to get various child nodes in the XML file, in detail the case:
Main class: Demo5.java
Package com.sax;
Import java.io.IOException;
Import java.util.ArrayList;
Import java.util.List;
Import javax.xml.parsers.ParserConfigurationException;
Import Javax.xml.parsers.SAXParser;
Import Javax.xml.parsers.SAXParserFactory;
Import org.xml.sax.Attributes;
Import org.xml.sax.SAXException;
Import Org.xml.sax.XMLReader;
Import Org.xml.sax.helpers.DefaultHandler;
public class Demo5 {
/**
* @param args
* @throws saxexception
* @throws parserconfigurationexception
* @throws IOException
*/
public static void Main (string[] args) throws Parserconfigurationexception,
Saxexception, IOException {
SAXParserFactory SPF = saxparserfactory.newinstance ();
SAXParser sp = Spf.newsaxparser ();
XMLReader reader = Sp.getxmlreader ();
Bookhandler bh = new Bookhandler ();
Reader.setcontenthandler (BH);
Reader.parse ("Src/book.xml");
list<book> list = Bh.getbook ();
for (book book:list) {
System.out.println (Book.getname () + "---" +book.getauthor () + "---" +book.getprice ());
}
}
}
Class Bookhandler extends DefaultHandler {
Private list<book> List = new arraylist<book> ();
Private String Currentname;
Private book book;
@Override
public void Startelement (string uri, String localname, String qName,
Attributes Attributes) throws Saxexception {
Currentname = QName;
if ("book". Equals (Currentname)) {
Book = new book ();
}
}
Public list<book> GetBook () {
return list;
}
public void characters (char[] ch, int start, int length)
Throws Saxexception {
if ("BookName". Equals (Currentname)) {
String value = new String (ch,start,length);
Book.setname (value);
}
if ("Author". Equals (Currentname)) {
String value = new String (ch,start,length);
Book.setauthor (value);
}
if ("Price". Equals (Currentname)) {
String value = new String (ch,start,length);
Book.setprice (value);
}
}
@Override
public void EndElement (string uri, String localname, String qName)
Throws Saxexception {
if ("book". Equals (QName)) {
List.add (book);
book = null;
}
Currentname = null;
}
}
Java Bean:book.java
Package com.sax;
public class Book {
private String name;
Private String author;
Private String Price;
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 GetPrice () {
return price;
}
public void Setprice (String price) {
This.price = Price;
}
}