Java uses Sax to parse XML files (common)

Source: Internet
Author: User

Perform the shipping from the URL below. Http://hck.iteye.com/blog/1175762

However, the program is slightly changed.

About SAX (from the encyclopedia)

Simple API for XML is an interface and a software package.

Sax is event-drivenA standard interface for XML parsing does not change the working principle of sax. Simply put, it scans documents sequentially. When a document is scanned) the event handler function is notified at the beginning and end, document ends, and so on. The event handler function performs the corresponding action and continues the same scan until the document ends.

Most sax generates the following types of events: 1. trigger a Document Processing Event at the beginning and end of the document. 2. Trigger element events before and after parsing Each XML Element in the document. 3. Any metadata is usually handled by a separate event 4. a dtd or schema event is generated when processing the document's DTD or schema. 5. An error event is generated to notify the Host application of parsing errors.

Common interfaces of Sax

Contenthandler Interface

Contenthandler is a special sax interface in a Java class package, which is located in the org. xml. Sax package. This interface encapsulates some event processing methods. When the XML Parser begins to parse the XML input file, it will encounter some special events, such as the beginning and end of a document, the beginning and end of an element, and the character data in an element. When these events occur, the XML Parser calls the corresponding method in the contenthandler interface to respond to the event.

The contenthandler interface has the following methods: void startdocument () void enddocument () void startelement (string Uri, string localname, string QNAME, attributes ATTS) void endelement (string Uri, string localname, string QNAME) void characters (char & amp; #91; & amp; #93; ch, int start, int length) dtdhandler interface, entityresolver interface, errorhandler interface, these three interfaces are useless. An example of the process of parsing a document using sax <Doc> <para> Hello, world! </Para> </DOC> the parsing process is as follows: 1. start document2.start element: Doc ...... 3. start Element: para ..... 4. characters: Hello, world! 5. end Element: para ...... 6.end element; doc ...... 7.end document triggers the event handler in the corresponding interface when an event occurs in every step of the parsing process. Let's look at a program.
<?xml version="1.0" encoding="GB2312"?>      <books  count="3" xmlns="http://test.org/books">          <!--books's comment-->          <book id="1">              <name>Thinking in JAVA</name>              <price>11</price>        </book>          <book id="2">              <name>Core JAVA2</name>              <price>22</price>        </book>          <book id="3">              <name>C++ primer</name>              <price>33</price>        </book>      </books>

// Book.javapublic class Book {    private int id;    private String name;    private double price;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public double getPrice() {        return price;    }    public void setPrice(double price) {        this.price = price;    }        public String toString(){        return "id = "+id + ",name = " + name + ",price = "+price;    }}

// BooksDefaultHandler.javaimport java.util.ArrayList;import java.util.List;import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler;public class BooksDefaultHandler extends DefaultHandler{    private List<Book> booklist;    private Book currentBook;    private String tag;        @Override    public void startDocument() throws SAXException {        booklist = new ArrayList<Book>();    }    @Override    public void startElement(String uri, String localName, String qName,            Attributes attributes) throws SAXException {        if("book".equals(localName)){            Integer id = new Integer(attributes.getValue(0));            currentBook = new Book();            currentBook.setId(id);        }        tag = localName;    }    @Override    public void characters(char[] ch, int start, int length)            throws SAXException {        if(tag != null){            String data = new String(ch,start,length);            if("name".equals(tag)){                currentBook.setName(data);            }else if ("price".equals(tag)){                Double price = new Double(data);                currentBook.setPrice(price);            }        }    }    @Override    public void endElement(String uri, String localName, String qName)            throws SAXException {        if("book".equals(localName)){            booklist.add(currentBook);            currentBook = null;        }        tag = null;    }        public List<Book> getBooklist() {        return booklist;    }}

// SAXBook.javaimport java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;import java.util.List;import org.xml.sax.ContentHandler;import org.xml.sax.InputSource;import org.xml.sax.SAXException;import org.xml.sax.XMLReader;import org.xml.sax.helpers.XMLReaderFactory;public class SAXBook {    public static void main(String[] args) throws FileNotFoundException, IOException, SAXException{                BooksDefaultHandler contentHandler = new BooksDefaultHandler();        XMLReader reader = XMLReaderFactory.createXMLReader();        reader.setContentHandler(contentHandler);          reader.parse(new InputSource(new FileReader("d:/90.Temp/books.xml")));                 List booklist = contentHandler.getBooklist();                for(Object book : booklist){            System.out.println((Book)book);        }                            }}

Output: Id = 1, name = thinking in Java, price = 11.0id = 2, name = core Java2, price = 22.0id = 3, name = C ++ primer, price = 33.0

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.