Parsing XML in Java

Source: Internet
Author: User
Tags xpath

Javain theXMLthe parsing1.dom4j

Dom parsing principle:The XML parser loads the XML document into memory at once, and then constructs a document object tree in Memory. Gets the node object on the tree through the document object, manipulating the document content through the node Object.

dom4j commonly used objects:

Saxreader: Reading an XML file to the document tree structure file Object

Document: an XML Document object tree that is analogous to an Html document Object.

element: Elements Node. You can find a single element by using the Document object

Steps to Use:

( import dom4j.jar package Dom4j-1.6.1.jar)

1. Create a saxreader parser

Saxreader Reader = new Saxreader ();

2. Get the Document object by using the read method

Document document = Reader.read ("conf/student.xml");
3. Get the root node

Element Rootele = document.getrootelement ();

4.4. iterating through an XML document through an iterator

Iterator it = Rootele.elementiterator ();

While (it.hasnext ()) {

Element Stusele = (element) It.next ();

Iterator it01 = Stusele.elementiterator ();

While (it01.hasnext ()) {

Element Stuele = (element) It01.next ();

System.out.println (stuele.getstringvalue ());

}

System.out.println ("--------------------------------");

}

DOM4J 's official documentation has quick start to help us quickly use the technology!

2.SAX

The Sax parsing tool is provided by sun, within the jdk . org.xml.sax.*;

Sax parsing principle: event-driven, read-side-write

When the start tag is encountered, the startelement (String url,string localname,string qname,attribute Attribute) method is called automatically ; automatically executes when text is encountered characters (char[]ch,int Start,int length); automatically executes when an end tag is encountered endElement (String url,string localname,string qName) Method.

< end tag with '/' as a flag, end method only one less attribute parameter than the Start method >

Steps to Use:

1. Create a resolution factory

The SAXParserFactory construction method is protected and can only be created by the . Newinstance () method

SAXParserFactory saxparserfactory = saxparserfactory.newinstance ();

2. Create a parser

creating a parser from the factory

SAXParser SAXParser = Saxparserfactory.newsaxparser ();

3. Implementing the Parser method

executes the parser method, passing in two parameters:xml file path, event handler

Saxparser.parse ("conf/student.xml", New Mydefaulthandler ());

The so-called event handler refers to a class that inherits from DefaultHandler , which is rewritten with startelement (),characters () , endElement () method to implement the corresponding Processing.

Create a class that inherits the Defaulthander class and overrides the three methods:

A, startelement get start tag, Important two parameter description

A, qName: Return the label name

b, attributes: Returns the Property object in the label

B, character get the label text content

C, endElement get end tag

============dom parsing vs SAX parsing ========

DOM parsing

SAX parsing

Principle: loading XML documents at once, not suitable for large-capacity file reads

Principle: load a little, read a little, handle a little. Suitable for large-capacity file reading

DOM parsing can be arbitrarily deleted and changed to

SAX parsing can only read

DOM parsing arbitrary reading of any location data, even reading backwards

SAX parsing can only be read from the top down, sequentially, and not read backwards

DOM parsing object-oriented programming methods (Node,Element,Attribute), Java The developer code is Simple.

SAX parses event-based programming methods. Java Development coding is relatively complex.

3.XPath

It is primarily used to quickly get the desired node Object.

Select Node:XPath uses a path expression to select a node in the XML document. Nodes are passed along the

Path or step to choose From. The most useful path expressions are listed Below:

Expression description

NodeName selects all child nodes of this Node.

/select from the root Node.

Selects the nodes in the document from the current node that matches the selection, regardless of their location.

. Select the current Node.

.. Selects the parent node of the current Node.

@ Select Properties.

Text () Gets the textual content function of the node

Steps to Use:

1. through Documentbuilderfactor Create a resolution factory

Documentbuilderfactory builderfactory = documentbuilderfactory

. newinstance ();

2. get the parser through the factory

Documentbuilder builder = Builderfactory.newdocumentbuilder ();

3. through Parser method gets Document

Document document = Builder.parse ("conf/books.xml");

4. Get XPath Object

XPath XPath = xpathfactory.newinstance (). newxpath ();

5. Get Bookstore node under book Properties category value is Web under the second title the text content of the node

String exp = "/bookstore/book[@category = ' web '][2]/title/text ()";

String tit = (string) xpath.evaluate (exp, document,

xpathconstants.string);

System.out.println (tit);

gets the bookstore node under the book property category value for the web of the Titile property is en the node content

String Expen = "/bookstore/book[@category = ' Web ']/title[@lang = ' en ']/text ()";

String titen = (string) xpath.evaluate (expen, document,

xpathconstants.string);

System.out.println (titen);

get bookstore the book attribute category value is cooking c8> The value of the lang property of the title

String Explan = "/bookstore/book[@category = ' Cooking ']/title/@lang";

string lang = (string) xpath.evaluate (explan, document,

xpathconstants.string);

System.out.println (lang);

gets The node collection for all book under the bookstore node (traversing the Document)

String EXPB = "/bookstore/book";

NodeList books = (NodeList) xpath.evaluate (expb, document, xpathconstants.nodeset);

for (int i = 0; i < books.getlength (); I++) {

Element book = (element) Books.item (i);

string title = (string) xpath.evaluate ("title/text ()", book, xpathconstants.string);

String author = (string) Xpath.evaluate ("author/text ()", book, xpathconstants.string);

String year = (string) xpath.evaluate (' year ', book, xpathconstants.string);

String price = (string) xpath.evaluate (' price ', book, xpathconstants.string);

System.out.println (title+ "" +author+ "" +year+ "" +price ");

System.out.println ("----------------------------------------------------");

}

4. indom4jused inXPath

dom4j and XPath are very flexible to use in development, so they are widely used!

Steps to Use:

1) import xpath support jar package  .    jaxen-1.1-beta-6.jar

2) using xpath method

List<node>  selectnodes ("xpath< Span style= "font-family: the song body;" > expression Querying multiple Node objects

Node       selectsinglenode ("xpath Querying a Node object

1.SAXReader Parser

Saxreader reader = new Saxreader ();

2. through Read method to obtain Document

Document Document =reader.read ("conf/bookstore.xml");

3.xpath Road Strength

String Titlepath = "/bookstore/book[1]/title";

Element element = (element) Document.selectobject (titlepath);

String title =element.getstringvalue ();

System.out.println (title);

Parsing XML in Java

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.