Study Notes - dom4j and sax

 SAX articles :

What is SAX : SAX, the full name of Simple API for XML, is both an interface and a software package. It is an alternative to XML parsing. In layman's terms, it is an interface used to parse xml files.

SAX Features : SAX is an event-driven "push" model for processing XML . The SAX parser does not build a complete document tree like the DOM, but activates a series of events when the document is read, which are pushed to the event Handlers, and event handlers then provide access to the document content. It scans the document line by line, parsing it as it scans. Since the application only checks the data as it is read, there is no need to store the data in memory, which is a huge advantage for parsing large documents .

Use of SAX :

public class SaxDemo {
        public static void main(String[] args) throws ParserConfigurationException, SAXException, Exception {
// TODO auto-generated method stub
// 1. Get its sax parser factory
    SAXParserFactory factory =SAXParserFactory. newInstance();
    / /2. Get the parser
    SAXParser parser=factory.newSAXParser();
       //3. Get the reader
    XMLReader reader = parser.getXMLReader();
       //4. Set the event handler for the reader, as can be seen from here sax is XML event driven for the model
    reader.setContentHandler(new DefaultHandler() {

public void characters(char[] ch, int start, int length) throws SAXException {
// TODO auto-generated method stub
/*ch - from XML The character of the document
start - the starting position in the
array length - the number of characters read from the array */ 
super.characters(ch, start, length);
System.out.println(new String(ch,start,length));

public void startDocument() throws SAXException {
// TODO auto-generated method stub
super.startDocument ();
System.out.println("document start");

public void endDocument() throws SAXException {
// TODO auto-generated method stub
System.out.println("docunment end" );

public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
// TODO auto-generated method stub
super.startElement(uri, localName, qName, attributes);
//qName is the element the qualified name, or empty if the qualified name is not available

public void endElement(String uri, String localName, String qName) throws SAXException {
// TODO 自动生成的方法存根
super.endElement(uri, localName, qName);
System.out.println("</"+qName+">");}    });       //5.读取文件    reader.parse("WebContent/WEB-INF/web.xml");}



Note: the functionality of sax is limited to reading files unlike dom4j below

DOM4j _

Definition of DOM4j :  DOM4J is an open source XML parsing package produced by DOM4J applies to the Java platform, uses the Java Collections framework and fully supports DOM, SAX and JAXP.

Function : According to my current learning experience, the function is to read and write xml files, and use SAX technology to read when reading.

Several core functions of DOM4J will be implemented through code:

First of all, all functions need to read the xml document, so the xml document can be encapsulated as a class and called directly.

Encapsulate document creation class

package dom4j.demo;

public class Dom4jCreateDocument {
public static Document getDocument(String uri) throws DocumentException {//参数为uri,这是xml文件的地址
            SAXReader reader=new SAXReader();
            Document document File(uri));
return document;




public class Dom4jwrite {

public static void write(Document document,String uri) throws Exception, FileNotFoundException
/* XMLWriter   writer =new XMLWriter(new OutputStreamWriter(new FileOutputStream("WebContent/WEB-INF/web.xml"), "utf-8"));*/
    XMLWriter writer =new XMLWriter(new FileOutputStream(uri),format);


public class Dom4jRead {

public static void main(String[] args) throws DocumentException {
Document document =Dom4jCreateDocument.getDocument("WebContent/WEB-INF/web.xml");
Element root =document.getRootElement();

Element element_1 =root.element("book");
Element element_2 =root.element("movie");
Element element_1_1=element_1.element("name");
Element element_2_2=element_2.element("auther");
List<Element> elements= element_1.elements();
Iterator<Element> itr=element_1.elementIterator();
Element list;
String text1=element_1_1.getText();
String text2=element_2_2.getText();
String id=element_1.attributeValue("id");



package dom4j.demo
public class Dom4jAdd {
public static void main(String[] args) throws DocumentException, Exception {
// TODO 自动生成的方法存根
Document document =Dom4jCreateDocument.getDocument("WebContent/WEB-INF/web.xml");
Element element =document.getRootElement().element("book");

    Element date=DocumentHelper.createElement("date");
    date.addAttribute("ch", "man");
    List<Element> list=element.elements();







package dom4j.demo;
public class Dom4jUpdate {

public static void main(String[] args) throws FileNotFoundException, Exception {
// TODO 自动生成的方法存根
Document document =Dom4jCreateDocument.getDocument("WebContent/WEB-INF/web.xml");
Element  root= document.getRootElement();
Element element=root.element("book").element("date");

Element element1=root.element("book");
element1.addAttribute("id", "2");//这里不是使用set方法而是add方法。

Dom4jwrite.write(document, "WebContent/WEB-INF/web.xml");



public class Dom4jRemove {

public static void main(String[] args) throws Exception {
// TODO 自动生成的方法存根
        Document document =Dom4jCreateDocument.getDocument("WebContent/WEB-INF/web.xml");
Element element =document.getRootElement().element("book").element("date");
Dom4jwrite.write(document, "WebContent/WEB-INF/web.xml");





package dom4j.demo;

public class Dom4jToString {

public static void main(String[] args) throws Exception {

String str=" <movie><name>杨瑞琦</name><auther>余飞</auther></movie> ";//要存入的内容

Document document =Dom4jCreateDocument.getDocument("WebContent/WEB-INF/web.xml");
Element element=document.getRootElement();
Document doc=DocumentHelper.parseText(str);

Dom4jwrite.write(document, "WebContent/WEB-INF/web.xml");





<?xml version="1.0" encoding="utf-8"?>
  <book id="2"> 


Guess you like