Java implements filtering nodes through XPath

Source: Internet
Author: User
Tags cdata xpath

First, the basic introduction

XPath is a language that looks up information in an XML document and can be used to traverse elements and attributes in an XML document. XPath is the main element of the XSLT standard for the consortium, and XQuery and XPointer are also built on XPath expressions. Therefore, the understanding of XPath is the foundation of many advanced XML applications. XPath is very similar to the SQL language for database operations, or jquery, which makes it easier for developers to grab what they need in a document. (Dom4j also supports XPath)

Second, node type

The so-called node, is the smallest constituent unit of the XML file, divided into 7 kinds altogether.

-Element (Elements node)
-Attributes (Attribute node)
-Text (literal node)
-Namespace (Namespace node)
-processing-instruction (Processing command node)
-Comment (annotation node)
-Root (Root node) three, Common path expressions

An expression Describe
Node name (nodename) Select all child nodes of this node
/ Selecting from the root node
// Select the nodes in the document from the current node of the matching selection, regardless of their location
. Select the current node
.. Select the parent node of the current node
@ Select Properties

wildcard characters

Describe
* Match any element node
@* Match any attribute node
Node () Match any type of node
| Select several paths

Iv. examples

Demo.xml

<?xml version= "1.0" encoding= "UTF-8"?> <rss version= "2.0" > <channel> <title>java Tutorials and Examples 2</title> <language>en-us</language> <item> <title><! [Cdata[java Tutorials 2]]></title> <link>http://www.javacodegeeks.com/</link> </item> &L T;item> <title><! [Cdata[java examples 2]]></title> <link>http://examples.javacodegeeks.com/</link> </item > </channel> <college name= "C1" > <class name= "Class1" > <student name= "stu1" sex= ' Male ' age=
		"<student"/> name= "stu2" sex= ' female ' age= ' "/> <student the Name=" Stu3 "sex= ' female ' age= '"/> "
			</class> </college> <bookstore> <book> <title lang= "eng" >harry potter</title>
			<price>29.99</price> </book> <book> <title lang= "eng" >learning xml</title> <price>39.95</price> </book> </bookstore> </rss> 

[Example 1] Bookstore: Select all child nodes of the bookstore element.

[Example 2]/bookstore: Select the root node bookstore, which is the absolute path notation.

[Example 3] Bookstore/book: Select all the book elements that belong to the bookstore, which is the relative path notation.

[Example 4]//book: Select all book child elements, regardless of their position in the document.

[Example 5] Bookstore//book: Select all the book elements that belong to descendants of the bookstore element, regardless of where they are located under bookstore.

[Example 6]//@lang: Select All properties named Lang.

conditional filtering: All conditions are written in square brackets "[]" to indicate further filtering of the node.

[Example 7]/bookstore/book[1]: Represents the first book child element of the selection bookstore.

[Example 8]/bookstore/book[last ()]: Represents the last book child element of the selection bookstore.

[Example 9]/bookstore/book[last ()-1]: Represents the penultimate book child element of the selected bookstore.

[Example]/bookstore/book[position () <3]: Represents the first two book child elements that select Bookstore.

[Example]//title[@lang]: Indicates that all title nodes with the lang attribute are selected.

[Example]//title[@lang = ' Eng ']: Represents the title node that selects all Lang attributes with a value equal to "eng".

[Case]/bookstore/book[price]: Represents the book child element that selects the bookstore, and the selected book element must have a price child element.

[Example]/bookstore/book[price>35.00]: Represents the book child element that selects the bookstore, and the price child element value of the selected book element must be greater than 35.

[Example]/bookstore/book[price>35.00]/title: In the example 14 result set, select the title child element.

[Example]/bookstore/book/price[.>35.00]: Indicates the price child element of "/bookstore/book" with a value greater than 35 selected. [Example 17]//*: Select all ELEMENT nodes in the document.

[Example 18]/*/*: Indicates that all second-level element nodes are selected.
[Example]/bookstore/*: Represents the selection of all element child nodes of the bookstore.
[Case]//title[@*]: Represents the selection of all title elements with attributes.

[Case]//book/title | Book/price: Represents the title child element and the price child element that selects the book element at the same time.

Code to implement XPath filtering in Java:

Import Java.io.File;

Import Java.io.FileInputStream;
Import Javax.xml.parsers.DocumentBuilder;
Import Javax.xml.parsers.DocumentBuilderFactory;
Import Javax.xml.xpath.XPath;
Import javax.xml.xpath.XPathConstants;
Import javax.xml.xpath.XPathExpressionException;

Import Javax.xml.xpath.XPathFactory;
Import org.w3c.dom.Document;
Import Org.w3c.dom.Node;

Import org.w3c.dom.NodeList;
	public class Xpathdemo {private static Document doc;

	private static XPath XPath;
		public static void Main (string[] args) throws Exception {init ();
		Getrootele ();
		Getchildeles ();
		Getparteles ();
		Havechildseles ();
		Getleveleles ();
		
		Getattreles ();
		Prints all element nodes under the root node System.out.println (doc.getdocumentelement (). Getchildnodes (). GetLength ());
		NodeList nodelist = Doc.getdocumentelement (). Getchildnodes (); for (int i = 0; i < nodelist.getlength (); i++) {if (Nodelist.item (i). Getnodetype () = = Node.element_node) {Syst
			Em.out.print (Nodelist.item (i). Getnodename () + ""); }}//earlyStart document, XPath object public static void Init () throws Exception {//Create Document object Documentbuilderfactory DBF = document
		Builderfactory.newinstance ();
		Dbf.setvalidating (FALSE);
		Documentbuilder db = Dbf.newdocumentbuilder ();

		doc = Db.parse (new FileInputStream ("Demo.xml"));
		Create an XPath object xpathfactory factory = Xpathfactory.newinstance ();
	XPath = Factory.newxpath (); //Get root element//expression can be replaced with/*,/rss public static void Getrootele () throws xpathexpressionexception {node node = (Node) x
		Path.evaluate ("/rss", Doc, Xpathconstants.node);
	System.out.println (Node.getnodename () + "--------" + node.getnodevalue ()); //Get child elements and print public static void Getchildeles () throws xpathexpressionexception {NodeList nodelist = (nodelist) xpat
		H.evaluate ("/rss/channel/*", Doc, Xpathconstants.nodeset);
		for (int i = 0; i < nodelist.getlength (); i++) {System.out.print (Nodelist.item (i) getnodename () + "");
	} System.out.println (); //Get part of element//Get element name only TITLThe elements of e are public static void Getparteles () throws xpathexpressionexception {NodeList nodelist = (nodelist) xpath.evaluate ("
		*[name () = ' title '] ', Doc, Xpathconstants.nodeset; for (int i = 0; i < nodelist.getlength (); i++) {System.out.print (Nodelist.item (i). Getnodename () + "-->" + N
		Odelist.item (i). Gettextcontent ());
	} System.out.println (); }//Get element with child node public static void Havechildseles () throws xpathexpressionexception {NodeList nodelist = (nodelist)
		Xpath.evaluate ("//*[*]", Doc, Xpathconstants.nodeset);
		for (int i = 0; i < nodelist.getlength (); i++) {System.out.print (Nodelist.item (i) getnodename () + "");
	} System.out.println (); //Gets the element public static void Getleveleles () of the specified level throws Xpathexpressionexception {NodeList nodelist = (nodelist) xpa
		Th.evaluate ("/*/*/*/*", Doc, Xpathconstants.nodeset); for (int i = 0; i < nodelist.getlength (); i++) {System.out.print (Nodelist.item (i). Getnodename () + "-->" + N OdeliSt.item (i). Gettextcontent () + "");
	} System.out.println ("-----------------------------");  //Gets the element of the specified property//Gets all bookcase public static void Getattreles () throws Xpathexpressionexception {NodeList nodelist, greater than the specified price
		= (nodelist) xpath.evaluate ("//bookstore/book[price>35.00]/title", Doc, Xpathconstants.nodeset); for (int i = 0; i < nodelist.getlength (); i++) {System.out.print (Nodelist.item (i). Getnodename () + "-->" + N
		Odelist.item (i). Gettextcontent () + "");
	} System.out.println (); }
}

Reference Documentation:

https://my.oschina.net/cloudcoder/blog/223359

Http://www.ruanyifeng.com/blog/2009/07/xpath_path_expressions.html

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.