Java Learning Summary (--xml) document parsing: Dom parsing, sax parsing

Source: Internet
Author: User
Tags tag name xml parser

A Introduction to XML
1. Extensible Markup Language (extensible Markup Language)
2.XML for describing data
3. Application:
(1) Persist data storage
(2) Data exchange
(3) Data configuration
4.XML syntax
(1) Document type:
When you write an XML document, you need to declare the type of the XML document using the document declaration.
The simplest declarative Syntax:
<? XML version= "1.0"?>
Use the Encoding property to describe the character encoding of the document:
<? XML version= "1.0" encoding= "GB2312"?>
(2) elements
For all whitespace and line breaks that appear in the XML tag, the XML parser processes the contents of the label, for example: the meanings of the following two paragraphs are different:

Since spaces and wraps are processed as raw content in XML, the "good" writing habit of using line wrapping and indentation to make the content readable in the original text can be forced to change when writing an XML file
(3) Notes
The comments in the XML file take the form "<!--annotation Content--"
Attention:
Cannot have comments before XML declaration
Annotations cannot be nested
(4) Format:
Must have an XML declaration statement
Must have and have only one root element
Label Case Sensitive
Attribute values in double or single quotation marks
Label pairs
element is nested correctly
Example 1 (Contact):
Use XML to describe the student score information in the following table, the XML file is Student.xml

The XML is represented as follows:

<?xml version="1.0" encoding="GBK"?><students>    <student>        <id>1</id>        <name>张同</name>        <subject>java</subject>        <score>89</score>    </student>    <student>        <id>2</id>        <name>李佳</name>        <subject>sql</subject>        <score>58</score>    </student></students>

Pull the file into the browser to see if it can be displayed:
Show Results:

Two DOM (doncument Object Model) parsing
1.DOM parsing is to replace the XML file in memory with a Document object model (often called the DOM tree), where the application can access any part of the data in the XML document at any time, so the mechanism of DOM parsing is also called the random access mechanism.
Note: Dom parsing has a higher need for memory
Steps for 2.DOM parsing:
(1) Establishing documentbuilderfactory

(2) Establishing Documentbuilder

(3) Document creation

(4) Establishing nodelist


(5) to read XML information
3.DOM Number Model

Example 2 (DOM parsing XML file, for example, we have just written the XML file):

Package Org.xml.dom;import Java.io.file;import Javax.xml.parsers.documentbuilder;import Javax.xml.parsers.documentbuilderfactory;import Org.w3c.dom.document;import Org.w3c.dom.nodelist;public Class Domparserdemo {public static void main (string[] args) {Documentbuilderfactory factory = Documentbuilderfactory        . newinstance ();//1. Building the DOM factory Documentbuilder builder = null; try {builder = Factory.newdocumentbuilder ();//2. Get DOM Parser Document document = Builder.parse ("E:" + File.separator + "Userinfo.xml");//3. Specify the parsed file path, parse the XML file into the DOM tree NodeList NodeList = document. getElementsByTagName ("province"); Gets the node that gets all the label names by tag name String value = Nodelist.item (3). Getfirstchild (). GETTEXTC            Ontent ();//Gets the contents of the node System.out.println ("The resolution node name is province in the third element is:" + value);        SYSTEM.OUT.PRINTLN ("Get node Name:" + Nodelist.item (3). Getnodename ());        } catch (Exception e) {e.printstacktrace ();   } }} 

Operation Result:

Example 3 (dynamically creating an XML file):

Package Org.xml.dom;import Java.io.file;import Javax.xml.parsers.documentbuilder;import Javax.xml.parsers.documentbuilderfactory;import Javax.xml.transform.outputkeys;import Javax.xml.transform.transformer;import Javax.xml.transform.transformerfactory;import Javax.xml.transform.dom.domsource;import Javax.xml.transform.stream.streamresult;import org.w3c.dom.Document; Import Org.w3c.dom.element;import Org.w3c.dom.text;public class Domcreatedemo {public static void main (string[] args)  {Documentbuilderfactory factory = Documentbuilderfactory.newinstance ();//1. Creating a DOM factory Documentbuilder builder        = NULL; try {builder = Factory.newdocumentbuilder ();//2. Get DOM parser Document doc = Builder.newdocument ();//3            . New Document Element students = doc.createelement ("Students");            Element student = doc.createelement ("student");            Element id = doc.createelement ("id");            Element name = doc.createelement ("name"); Element Subject = Doc.createelement ("subject");            Element score = doc.createelement ("score");            Text Idtext = Doc.createtextnode ("1");            Text Nametext = Doc.createtextnode ("Wang Zhaojun");            Text Subjecttext = Doc.createtextnode ("java");            Text Scoretext = Doc.createtextnode ("99.4");            Students.appendchild (student);            Student.appendchild (ID);            Student.appendchild (name);            Student.appendchild (subject);            Student.appendchild (score);            Id.appendchild (Idtext);            Name.appendchild (Nametext);            Subject.appendchild (Subjecttext);            Score.appendchild (Scoretext);            Doc.appendchild (students);            Transformerfactory Factory2 = Transformerfactory.newinstance ();            Transformer tf = Factory2.newtransformer ();            Tf.setoutputproperty (outputkeys.indent, "yes");//Automatic line-wrapping Tf.setoutputproperty (outputkeys.encoding, "GBK"); Domsource soure = new DomsourCE (DOC);//Generate Domsource inside contains Doc object Streamresult rs = new Streamresult ("F:" + File.separator + "Student.xml"));//streamresult encapsulates the target output file Tf.transform (Soure, RS);//Start Writing System.out.println ("        Student.xml file generation succeeded ... ");        } catch (Exception e) {e.printstacktrace (); }    }}

Operation Result:

Three SAX (Simple APIs for XML) parsing
1.SAXs is an XML event-driven "push" model that activates a series of events when reading a document, which is pushed to the event handler and then provided access to the document content by the event handler
2. Typically used to find, read XML data
3.SAX parsing steps:
(1) Write the SAX parser, which inherits from the Defaulthanderler class, while covering related methods
(2) Establishing a sax parsing plant:

(3) Construct the parser:

(4) Parsing xml:

Example 4 (parsing an XML document with sax):
(1) Custom SAX parser

Package Org.xml.saxdemo;import Org.xml.sax.attributes;import Org.xml.sax.saxexception;import org.xml.sax.helpers.defaulthandler;//The custom parser public class Mysaxhandler extends DefaultHandler {///document is automatically called when the method starts parsing @Ove    Rride public void Startdocument () throws Saxexception {System.out.println ("XML document begins parsing:"); This method is automatically called when the element is parsed @Override public void startelement (string uri, String localname, String qName, at        Tributes attributes) throws Saxexception {System.out.print ("<" + QName);                     for (int i = 0; i < attributes.getlength (); i++) {System.out.print ("" + attributes.getlocalname (i) + "=\")        + Attributes.getvalue (i) + "\" ");    } System.out.print (">"); }//element parsing ends when the method is called automatically @Override public void EndElement (string uri, String localname, string qName) throw    S saxexception {System.out.print ("</" + QName + ">"); The method is called automatically when parsing text data @Override public void ChaRacters (char[] ch, int start, int length) throws Saxexception {System.out.print (New String (CH, start, L    Ength)); The method is called automatically at the end of document resolution @Override public void Enddocument () throws Saxexception {System.out.println ("End of document parsing:    "); }}

(2) Test parsing XML file

package org.xml.saxdemo;import java.io.File;import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;public class SAXDemo {    public static void main(String[] args) {        MySAXHandler handler=new MySAXHandler();        //1.建立sax解析工厂        SAXParserFactory factory=SAXParserFactory.newInstance();        //2.构造解析器        try {            SAXParser parser=factory.newSAXParser();            //3.解析XML            parser.parse("e:"+File.separator+"userinfo.xml",handler );        } catch (Exception e) {            e.printStackTrace();        }     }}

Operation Result:

Example 5 (parsing an XML document and encapsulating it as a JavaBean object):
(1) Write JavaBean code:
User object:

package org.xml.saxbean2;import java.util.List;public class User {    private String id;    private String name;    private List<Address> adds;    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 List<Address> getAdds() {        return adds;    }    public void setAdds(List<Address> adds) {        this.adds = adds;    }    @Override    public String toString() {        return "User [id=" + id + ", name=" + name + ", adds=" + adds + "]";    }}

Address object:

package org.xml.saxbean2;public class Address {    private String type;    private String province;    private String city;    public String getType() {        return type;    }    public void setType(String type) {        this.type = type;    }    public String getProvince() {        return province;    }    public void setProvince(String province) {        this.province = province;    }    public String getCity() {        return city;    }    public void setCity(String city) {        this.city = city;    }    @Override    public String toString() {        return "Address [type=" + type + ", province=" + province + ", city="                + city + "]";    }}

(2) Custom parser:

Package Org.xml.saxbean2;import Java.util.*;import Org.xml.sax.attributes;import org.xml.sax.saxexception;import    org.xml.sax.helpers.defaulthandler;//SAX Parser public class Mysaxhandler extends DefaultHandler {private user user;    private address address;    Private list<address> AddressList;    Private list<user> userlist; private String text; The method is called automatically when the text//XML document is stored to start parsing @Override public void startdocument () throws Saxexception {System.out.printl    N ("Start reading XML document:"); The method is called automatically when parsing a document element @Override public void startelement (string uri, String localname, String qName, A Ttributes attributes) throws Saxexception {if ("Users". Equals (QName)) {userlist = new Arraylist<use        R> ();        } else if ("User". Equals (QName)) {user = new user ();        } else if ("adds". Equals (QName)) {AddressList = new arraylist<address> (); } else if ("Address". Equals (QName)) {address = new Address ();        Address.settype (attributes.getvalue (0)); Called @Override public void characters (char[] ch, int start, int length) when parsing text data throws Saxexcep    tion {text = new String (CH, start, length); }//element begins to call when parsing is complete @Override public void endElement (string uri, String localname, String qName) throws S        axexception {if ("id". Equals (QName)) {User.setid (text);        } else if ("name". Equals (QName)) {user.setname (text);        } else if ("Province". Equals (QName)) {address.setprovince (text);        } else if ("City". Equals (QName)) {address.setcity (text);        } else if ("Address". Equals (QName)) {Addresslist.add (address);        } else if ("adds". Equals (QName)) {User.setadds (AddressList);        } else if ("User". Equals (QName)) {userlist.add (user); }}//document parsing is complete when you start calling @Override public void Enddocument () throws Saxexception {for (user user:userlist) {System.out.println (user); }    }}

(3) test code

package org.xml.saxbean2;import java.io.File;import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;public class SAXDemo {    public static void main(String[] args) {        SAXParserFactory factory=SAXParserFactory.newInstance();        try {            SAXParser parser=factory.newSAXParser();            parser.parse(new File("e:"+File.separator+"userinfo.xml"),new MySAXHandler());        } catch (Exception e) {            e.printStackTrace();        }    }}

Operation Result:

Example 5 (parse the network XML document for the current weather forecast):
(1) Compiling the weather forecast JavaBean
(2) Custom SAX parser
(3) Test sax parsing to get current weather information

Java Learning Summary (--xml) document parsing: Dom parsing, sax parsing

Related Article

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.