Introduction to XPath - Using XPath
(Page 4 of 4 )
We learned about XPath expressions in the previous section. Now we will learn how to use XPath in some common programming languages.
Here is some example code for VBScript.
set xmlDoc=CreateObject("Microsoft.XMLDOM")
xmlDoc.async="false"
xmlDoc.load("books.xml")
xmlDoc.setProperty "SelectionLanguage", "XPath"
xmlDoc.selectNodes(path expression)
First create an object of Microsoft.XMLDOM. Then load the XML document. After that set the SelectionLanguage property as equal to XPath. Then select nodes using your path expression.
The main interface for using XPath is the evaluate function of the document object in JavaScript. The syntax of the evaluate function returns XPathResultobject -
var xpathResult = document.evaluate(
xpathExpression,
contextNode,
namespaceResolver,
resultType,
result);
xpathExpression is a string representing the XPath to be evaluated. contextNode is the node inside which the search will take place. document is the most common. namespaceResolver is a function that will be passed any namespace prefixes and should return a string representing the namespace URI associated with that prefix. null is common for HTML documents or when no namespace prefixes are used. resultType is an integer that corresponds to the type of result XPathResult to return. Use XPathResult.ANY_TYPE as default. result is an existing XPathResult to use for the results. null is the most common and will create a new XPathResult
var books = document.evaluate("/book/title", document, null, XPathResult.ANY_TYPE, null);
var thisBook = books.iterateNext();
var alertText = "Book titles are:n"
while (thisBook) {
alertText += thisBook.textContent + "n"
thisBook = books.iterateNext();
}
alert(alertText);
First we get the XPathResult object as books for the XPath expression /book/title. Then we iterate through the list and get the textContent of the node.
In C#, you canselect and locate XML nodes and navigate through them usingXPathNavigatorandXPathNodeIterator. Here is a simple example.
using System.Xml;
using System.Xml.XPath;
...
String filename = "data.xml";
XPathDocument doc = new XPathDocument(filename);
XPathNavigator nav = doc.CreateNavigator();
XPathExpression exp = nav.Compile("/book/year");
XPathNodeIterator iter = nav.Select(exp);
try
{
while (iterator.MoveNext())
{
XPathNavigator nav2 = iterator.Current.Clone();
Console.WriteLine("price: " + nav2.Value);
}
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
First we include the references/namespaces. Then we create a new XPathDocument and XPathNavigator using XPathDocument. Next we Compile the path expression. After that we create the iterator to iterate through the XML tree. If the iterator has more elements, we create a new navigator using the current node. We then get the value of this new navigator.
From JDK 1.5, Java has built in support for XPath. To use XPath you first need to import the javax.xml.xpath.* package. Here is some sample code for Java.
/**
* @(#)xpath.java
*
*
* @author
* @version 1.00 2007/7/22
*/
import javax.xml.xpath.*;
import org.xml.sax.InputSource;
public class xpath {
/**
* Creates a new instance of <code>xpath</code>.
*/
public xpath() {
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
String expression = "/book[@id=1]/price";
InputSource iSource;
try
{
iSource = new InputSource("book.xml");
}
catch(Exception e)
{
e.printStackTrace(System.out);
}
XPath xpath = XPathFactory.newInstance().newXPath();
try{
String output = xpath.evaluate(expression, iSource);
System.out.println(output);
}
catch(XPathExpressionException e)
{
e.printStackTrace(System.out);
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
}
In above example we are trying to get the price of the <book> element which has an id attribute equal to 1. First we import the necessary packages. We then create an XPath object using XPathFactory.newInstance().newXPath(). To evaluate a path expression we need the XML document. The evaluate function of the xpath object takes path expression and an InputSource as input and returns the node. For InputSource, you can specify the file name of the XML document. If the evaluate function fails to evaluate the expression, it throws an XPathExpressionException. After evaluating the expression in the example above, we print the result in standard output.
I tried to focus on XPath expressions and how to use them in different programming languages. I hope you found this helpful.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |