XPath Tutorial: a go through

Like file path work in window or Linux OS, XPath work for a XML document.  It helps in finding information within XML document. Many items are not described if it matches exactly with CSS selectors.

There are seven types of nodes: element, attribute, text, namespace, processing-instruction, comment, and document(root) nodes.

Atomic values: Atomic values are nodes with no children or parent. Text Nodes and attributes value are atomic value.

Items: are atomic values or nodes.

Selecting Nodes

Expression      Desc
nodename     Selects all child nodes of the named node
/     Selects from the root node
//     Selects from current node that match the selection
.     Current node
..     Parent Node

Predicates: It is used to find a specific node or node that contains a specific value. Predicates are embedded in square brackets.

Example usage of predicate:
/bookstore/book[0]  = Selects 1st book child element of bookstore. IE and later has implemented 0 as 1st node but w3c standard is 1 for 1st.

/bookstore/book[last()]         -       Select the last book child element of bookstore

/bookstore/book[last()-1]       -       2nd last
/bookstore/book[position()<3]   -       Select first 2 book elements
//title[@lang]
//title[@last='eng']
/bookstore/book[price>35.00]
/bookstore/book[price>35.00]/title

Wildcards
*          = all
@*      = Matches any attribute node
node()  = Matches any node of any kind

| is used for OR

Axis: Axis defines node-select relative to the current node.

AxisName         Result
ancestorSelect all ancestors (parent, grandparents, etc) of the current node
ancestor-or-self  -
attributeSelect all attributes of the current node
childSelect all children of the current node
descendent-
descendent-or-self-
followingSelect everything in the current doc after the closing tag of the current node
following-siblingSelect all sibling of the current node
namespaceSelect all namespace nodes of the current node
parentParent of the current node
precedingSelect everything before the current node
preceding-siblingSelect all sibling befor the current node
selfSelect the current node

Usage:

child::book
attribute::lang
child::*
attribute::*
child::text()
child::node()
descendent::book

XPath Operators:
XPath expression returns either a node-set, boolean, a string, or a number.

Operators:
|
+
-
*       means Multiply
div   means Division
=
!=
<
>
<=
>=
>
or
and
mod =   Modulus(division remainder)

Load XML doc
var xmlhttp=new XMLHttpRequest()
For IE 5 and 6
var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")

xmlhttp.open("GET",dname,false);
xmlhttp.send("");
xmlDoc = xmlhttp.responseXML;

Selecting node

// Non-IE
xmlDoc.evaluate(xpath, xmlDoc, null, XPathResult.ANY_TYPE,null);
// IE only
xmlDoc.selectNodes(xpath);

Reference:
W3Schools