In-depth XPath detailed and Java Sample Code Analysis _java

Source: Internet
Author: User
Tags processing instruction xpath xquery
Copy Code code as follows:



Import java.io.IOException;


Import javax.xml.parsers.*;


Import javax.xml.xpath.*;


Import org.w3c.dom.*;


Import org.xml.sax.SAXException;


public class Xpathtest {


public static void Main (string[] args) throws Parserconfigurationexception,


Saxexception, IOException, xpathexpressionexception {


Documentbuilderfactory factory = Documentbuilderfactory.newinstance ();


Factory.setnamespaceaware (FALSE);


Documentbuilder builder = Factory.newdocumentbuilder ();


Document doc = Builder.parse ("C:/users/administrator/desktop/test.xml");


System.out.println (Doc.getchildnodes (). GetLength ());


Xpathfactory xfactory = Xpathfactory.newinstance ();


XPath XPath = Xfactory.newxpath ();


XPathExpression expr = XPath


. Compile ("//name/text ()");


Object result = Expr.evaluate (doc, Xpathconstants.nodeset);


NodeList nodes = (nodelist) result;


System.out.println (Nodes.getlength ());


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


System.out.println (Nodes.item (i). Getnodevalue ());


}


}


}





type of node
There are seven kinds of node types in XPath: element, attribute, text, namespace, processing instruction, comment, and document node (or root node). The root node of the document is the document node, the corresponding attribute has the attribute node, and the element has the element node.


ii. Common path expressions
Description of expression


NodeName Select all child nodes of this node


/Select from 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


@ Pick Properties


For example, there are documents:


Copy Code code as follows:

<?xml version= "1.0" encoding= "Iso-8859-1"?>
<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>



The


Path expression Results


Bookstore Select all child nodes of the bookstore element


/bookstore Select the root element bookstore annotation: If the path starts with a forward slash (/), this path always represents an absolute path to an element!


Bookstore/book selects all the book elements that belong to the bookstore child element.


Book selects all book child elements, regardless of their position in the document.


Bookstore//book selects all the book elements that belong to descendants of the bookstore element, regardless of where they are located under bookstore.


@lang Select All properties named Lang.


Iii. Qualifying language
A node that is used to find a particular node or that contains a specified value. Enclosed in square brackets.


For example:


Path expression Results


/BOOKSTORE/BOOK[1] Selects the first book element that belongs to the bookstore child element.


/bookstore/book[last ()] selects the last book element that belongs to the bookstore child element.


/bookstore/book[last ()-1] selects the penultimate book element that belongs to the bookstore child element.


/bookstore/book[position () &lt;3] selects the book element with the first two child elements that belong to the bookstore element.


title[@lang] Select all title elements that have properties named Lang.


title[@lang = ' eng '] selects all the title elements, and these elements have the lang attribute with the value eng.


/bookstore/book[price&gt;35.00] selects the book element of all bookstore elements, and the value of the price element must be greater than 35.00.


/bookstore/book[price&gt;35.00]/title selects the title element of the book element in all bookstore elements, and the value of the price element must be greater than 35.00.


four, wildcard characters
Wildcard description


* Match any element node


@* matches any attribute node


Node () matches nodes of any type


| Select several paths


For example:


Path expression Results


/bookstore/* Select all child nodes of the bookstore element


* Select all elements in the document


TITLE[@*] Selects all the title elements with attributes.


Book/title | Book/price selects the Tilte and price elements of all book elements.


Title | Price selects the title and price elements in all documents.


/bookstore/book/title | Price selects all the title elements of the book element that belong to the bookstore element, and all the price elements in the document.





Five, function
Name results


Ancestor Select all ancestors of the current node (parent, grandfather, etc.)


Ancestor-or-self selects all ancestors of the current node (parent, grandfather, etc.) and the current node itself


Attribute Select all properties of the current node


The child selects all children of the current node.


Descendant selects all descendant elements (child, grandchild, etc.) of the current node.


Descendant-or-self selects all descendant elements (child, grandchild, etc.) of the current node and the current node itself.


Following selects all nodes after the end tag of the current node in the document.


Namespace Select all namespace nodes for the current node


Parent selects the parents node of the current node.


Preceding selects all nodes before the start tag of the current node in the document.


Preceding-sibling selects all sibling nodes before the current node.


Self selects the current node.


A path expression can be either an absolute path or a relative path. For example:


Absolute location Path:
/step/step/... Relative location path:


step/step/... Each of these steps can be an expression, including:


Axes (functions) (axis)


Defines the tree relationship between the selected node and the current node


Node Test (node-test)


Identify the nodes within an axis


0 or more predicates (predicate)


Refine the selected node set more deeply


Example: Example results
Child::book Select all the book nodes that belong to the child element of the current node


Attribute::lang Select the lang attribute of the current node


Child::* Select all children of the current node


Attribute::* Select all properties of the current node


Child::text () selects all text child nodes of the current node


Child::node () selects all child nodes of the current node


Descendant::book Select all book descendants of the current node


Ancestor::book selects all ancestors of the current node


Ancestor-or-self::book selects all ancestors of the current node and the current node (false so that the node is the book node)


Child::*/child::p Rice Select all the price grandchildren for the current node.


VI, operator
Operator Description instance return value


| Compute two node sets//book | CD returns all node sets with book and CK elements


+ addition 6 + 4 10


-Subtraction 6-4 2


* Multiplication 6 * 4 24


Div Division 8 Div 4 2


= equals price=9.80 Returns True if Price is 9.80. If Price is 9.90, return Fasle.


!= is not equal to price!=9.80 returns True if Price is 9.90. If Price is 9.98, return Fasle.


&lt; less than price&lt;9.80 if Price is 9.00, returns True if Price is 9.98, return Fasle


&lt;= is less than or equal to price&lt;=9.80 returns True if Price is 9.00. If Price is 9.90, return Fasle.


&gt; Greater than price&gt;9.80 returns True if Price is 9.90. If Price is 9.80, return Fasle.


&gt;= is greater than or equal to price&gt;=9.80 returns True if Price is 9.90. If Price is 9.70, return Fasle.


Or or price=9.80 or price=9.70 returns True if Price is 9.80. If Price is 9.50, return Fasle.


And with price&gt;9.00 and price&lt;9.90 returns True if Price is 9.80. If Price is 8.50, return Fasle.


MoD calculates the remainder of Division 5 mod 2 1





Vii. using XPath in Java
A Javax.xml.xpath package was introduced in java1.5 to read XML using XPath expressions in Java. 1. Data type


The first thing to note before learning is that XPath data does not correspond to Java one by one, and Xpath1.0 only declares four types of data:


Node-set


number


Boolean


string





Corresponding to Java is:


number map to Java.lang.Double


string Map to Java.lang.String


Boolean map to Java.lang.Boolean


Node-set Map to Org.w3c.dom.NodeList





Therefore, when using Java Xpathapi, you need to be aware of the return type:


Java code


Copy Code code as follows:

The public object Evaluate (object item, QName returntype) throws xpathexpressionexception;

Public String Evaluate (Object) throws xpathexpressionexception;

Public Object Evaluate (InputSource source, QName ReturnType) throws xpathexpressionexception;

Public String Evaluate (InputSource source) throws Xpathexpressionexception;



Copy Code code as follows:

The public object Evaluate (object item, QName returntype) throws xpathexpressionexception;

Public String Evaluate (Object) throws xpathexpressionexception;

Public Object Evaluate (InputSource source, QName ReturnType) throws xpathexpressionexception;

Public String Evaluate (InputSource source) throws Xpathexpressionexception;



When you do not specify a return type, the default return type is String. When specifying a return type, you need to cast the return value from the object type to the corresponding return type.


Use of the API


Like DOM, to get an XPath object, you can use the following: Java code


Copy Code code as follows:

Xpathfactory factory = Xpathfactory.newinstance ();
XPath XPath = Factory.newxpath ();
XPathExpression expression = Xpath.compile ("/bookstore//book/title/text ()");



Copy Code code as follows:

<strong><strong> Xpathfactory factory = Xpathfactory.newinstance ();
XPath XPath = Factory.newxpath ();
XPathExpression expression = Xpath.compile ("/bookstore//book/title/text ()");</strong></strong>



Take the previous XML document as an example. To get the result of this expression, we first need to get an input object, such as a document:


Copy Code code as follows:

Documentbuilderfactory builderfactory = Documentbuilderfactory.newinstance ();
Documentbuilder Documentbuilder = Builderfactory.newdocumentbuilder ();
Document document = Documentbuilder.parse (new File ("books.xml"));
NodeList list = (nodelist) expression.evaluate (Document,xpathconstants.nodeset);



Copy Code code as follows:

<strong><strong> documentbuilderfactory builderfactory = Documentbuilderfactory.newinstance ();
Documentbuilder Documentbuilder = Builderfactory.newdocumentbuilder ();
Document document = Documentbuilder.parse (new File ("books.xml"));
NodeList list = (nodelist) expression.evaluate (document,xpathconstants.nodeset);</strong></strong>



As you can see, when using XPath, it seems like we need to know exactly what the return result is. Otherwise, the desired result cannot be obtained.


Finally, we get a list value of title:


Copy Code code as follows:

for (int i = 0;i<list.getlength (); i++) {System.out.println (List.item (i) getnodevalue ());
}



Copy Code code as follows:

<strong><strong> for (int i = 0;i</strong></strong>



Copy Code code as follows:

Everyday Italian
Harry Potter
XQuery Kick Start
Learning XML



Copy Code code as follows:

<strong><strong>everyday Italian
Harry Potter
XQuery Kick Start
Learning xml</strong></strong>



viii. Processing command space generally a specification XML will have a namespace definition, for example:
Copy Code code as follows:

<strong><strong>


Hello

</strong></strong>



Copy Code code as follows:

<?xml version= "1.0" encoding= "UTF-8"?>
<tg:bookstore xmlns:tg= "Http://www.tibco.com/cdc/liugang"
xmlns:ns= "Http://www.tibco.com/cdc/liugang/ns" >
<ns:book>
<tg:title>Hello</tg:title>
</ns:book>
</tg:bookstore>



Three functions related to node name and namespace are defined in XPath:


Local-name ()


Namespace-uri ()


name ()


For example, to find all the nodes that have the local name book for the element defined in the current document, the following are:


Copy Code code as follows:

Xpathfactory xpathfactory = Xpathfactory.newinstance ();
XPath XPath = Xpathfactory.newxpath ();
XPathExpression compile = Xpath.compile ("//*[local-name () = ' book '");
NodeList list = (nodelist) compile.evaluate (Document,xpathconstants.nodeset);



Copy Code code as follows:

<strong><strong> xpathfactory xpathfactory = Xpathfactory.newinstance ();
XPath XPath = Xpathfactory.newxpath ();
XPathExpression compile = Xpath.compile ("//*[local-name () = ' book '");
NodeList list = (nodelist) compile.evaluate (document,xpathconstants.nodeset);</strong></strong>



If the element defines a namespace, it must also be specified in the same namespace when using XPath lookup, even if the element uses the default namespace, and the default namespace needs to be defined just to find. For example, document:


Copy Code code as follows:



&lt;?xml version= "1.0" encoding= "UTF-8"?&gt;


&lt;bookstore xmlns= "Http://www.tibco.com/cdc/liugang" xmlns:tg= "HTTP://WWW.TIBCO.COM/CDC/LIUGANG/TG"


xmlns:ns= "Http://www.tibco.com/cdc/liugang/ns" &gt;


&lt;ns:book&gt;


&lt;tg:title&gt;Hello&lt;/tg:title&gt;


&lt;/ns:book&gt;


&lt;computer&gt;


&lt;id&gt;ElsIOIELdslke-1233&lt;/id&gt;


&lt;/computer&gt;


&lt;/bookstore&gt;





Copy Code code as follows:

<strong><strong>


Hello


ElsIOIELdslke-1233

</strong></strong>



Three namespaces defined: default; Xmlns:tg;xmlns:ns. To use namespaces, we need to set the namespace context for XPath: Namespacecontext. This is an interface type and we need to customize it to implement it. For example, the three namespaces that correspond to the previous document can be implemented as follows:


Copy Code code as follows:



Class Customnamespacecontext implements namespacecontext{





public string Getnamespaceuri (string prefix) {


if (Prefix.equals ("ns")) {


return "Http://www.tibco.com/cdc/liugang/ns";


}else if (prefix.equals ("TG")) {


return "HTTP://WWW.TIBCO.COM/CDC/LIUGANG/TG";


}else if (prefix.equals ("df")) {


return "Http://www.tibco.com/cdc/liugang";


}


return Xmlconstants.null_ns_uri;


}





public string Getprefix (string NamespaceURI) {


return null;


}





Public iterator getprefixes (String NamespaceURI) {


return null;


}





}





Copy Code code as follows:



&lt;strong&gt;&lt;strong&gt;class Customnamespacecontext implements namespacecontext{





public string Getnamespaceuri (string prefix) {


if (Prefix.equals ("ns")) {


return "Http://www.tibco.com/cdc/liugang/ns";


}else if (prefix.equals ("TG")) {


return "HTTP://WWW.TIBCO.COM/CDC/LIUGANG/TG";


}else if (prefix.equals ("df")) {


return "Http://www.tibco.com/cdc/liugang";


}


return Xmlconstants.null_ns_uri;


}





public string Getprefix (string NamespaceURI) {


return null;


}





Public iterator getprefixes (String NamespaceURI) {


return null;


}





}&lt;/strong&gt;&lt;/strong&gt;





Method names are very intuitive. Only the first method is implemented here. Thus, if you are looking for a namespace that is the default, all elements of element name computer can be implemented as follows:


Copy Code code as follows:

Xpathfactory xpathfactory = Xpathfactory.newinstance ();
XPath XPath = Xpathfactory.newxpath ();
Xpath.setnamespacecontext (New Customnamespacecontext ());
XPathExpression compile = Xpath.compile ("//df:computer");
NodeList list = (nodelist) compile.evaluate (Document,xpathconstants.nodeset);
for (int i = 0;i
Node item = List.item (i);
System.out.println (Item.getnodename () + "" +item.getnodevalue ());
}



Copy Code code as follows:

<strong><strong> xpathfactory xpathfactory = Xpathfactory.newinstance ();
XPath XPath = Xpathfactory.newxpath ();
Xpath.setnamespacecontext (New Customnamespacecontext ());
XPathExpression compile = Xpath.compile ("//df:computer");
NodeList list = (nodelist) compile.evaluate (Document,xpathconstants.nodeset);
for (int i = 0;i</strong></strong>



IX, other


In addition, in Java, you can also define an extended function interpreter and a variable interpreter, looking at the XPath method:


Copy Code code as follows:



/**


*


Establish a variable resolver.





*


*


A NullPointerException is thrown if resolver is null.





*


* @param resolver Variable Resolver.


*


* @throws nullpointerexception If resolver is null.


*/


public void Setxpathvariableresolver (Xpathvariableresolver resolver);








/**


*


Establish a function resolver.





*


*


A NullPointerException is thrown if resolver is null.





*


* @param resolver XPath function Resolver.


*


* @throws nullpointerexception If resolver is null.


*/


public void Setxpathfunctionresolver (Xpathfunctionresolver resolver);





Copy Code code as follows:



&lt;strong&gt;&lt;strong&gt;/**


* Establish a variable resolver.


*


* A &lt;code&gt;NullPointerException&lt;/code&gt; is thrown if &lt;code&gt;resolver&lt;/code&gt; is &lt;code&gt;null &lt;/code&gt;.


*


* @param resolver Variable Resolver.


*


* @throws nullpointerexception If &lt;code&gt;resolver&lt;/code&gt; is &lt;code&gt;null&lt;/code&gt;.


*/


public void Setxpathvariableresolver (Xpathvariableresolver resolver);








/**


* Establish a function resolver.


*


* A &lt;code&gt;NullPointerException&lt;/code&gt; is thrown if &lt;code&gt;resolver&lt;/code&gt; is &lt;code&gt;null &lt;/code&gt;.


*


* @param resolver XPath function Resolver.


*


* @throws nullpointerexception If &lt;code&gt;resolver&lt;/code&gt; is &lt;code&gt;null&lt;/code&gt;.


*/


public void Setxpathfunctionresolver (Xpathfunctionresolver resolver);&lt;/strong&gt;&lt;/strong&gt;





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.