Welcome!

Virtualization Authors: Frank Huerta, Pieter Van Heck, Gary Kaiser, Elizabeth White, Pat Romanski

Related Topics: Oracle, Java, XML

Oracle: Article

XPath Support in Oracle JDeveloper 11g

JDeveloper provides an XPath Search GUI tool to select nodes from an XML document using XPath

XML documents can be used to transfer data. The data in an XML document can be retrieved either with the JAXP (Java API for XML Processing) DOM and SAX APIs, or with the JAXP XPath API. Addressing an XML document with XPath has the advantage of selecting a single node directly without iterating over a node set. In this article, we'll explore XPath support in Oracle JDeveloper-XDK 11g. The article is a book extract from Packt Publishing's Processing XML Documents in Oracle JDeveloper 11g.

With SAX and DOM APIs, node lists have to be iterated to access a particular node. Another advantage of navigating an XML document with XPath is that an attribute node may be selected directly. With DOM and SAX APIs, an element node has to be selected before an element attribute can be selected. Here we'll discuss XPath support in JDeveloper.

What Is XPath?
XPath is a language for addressing an XML document's elements and attributes. For instance, say you get an XML document that contains details of a shipment and you want to retrieve the element/attribute values from it. You don't just want to list the values of all the nodes; you want to output the values of specific elements or attributes too. In such a case, you'd use XPath to retrieve the values of those elements and attributes. XPath constructs a hierarchical structure of an XML document, a tree of nodes that's the XPath data model. The XPath data model consists of seven node types. The different types of nodes in the XPath data model are discussed in Table 1.

Specific nodes including element, attribute, and text nodes can be accessed with XPath. XPath supports nodes in a namespace. Nodes in XPath are selected with an XPath expression. An expression is evaluated to yield an object of one of the following four types: node set, Boolean, number, or string.

For an introduction to XPath refer to the W3C Recommendation for XPath. As a brief review, expression evaluation in XPath is performed with respect to a context node. The most commonly used type of expression in XPath is a location path. XPath defines two types of location paths: relative location paths and absolute location paths. A relative location path is defined with respect to a context node and consists of a sequence of one or more location steps separated by "/". A location step consists of an axis, a node test, and predicates. An example of a location step is:

child::journal[position()=2]

In this example, the child axis contains the child nodes of the context node. Node test is the journal node set, and the predicate is the second node in the journal node set. An absolute location path is defined with respect to the root node, and starts with "/". The difference between a relative location path and an absolute location path is that a relative location path starts with a location step and an absolute location path starts with "/".

XPath in Oracle XDK 11g
Oracle XML Developer's Kit 11g, which is included in JDeveloper, provides the DOMParser class to parse an XML document and construct a DOM structure of the XML document. An XMLDocument object represents the DOM structure of an XML document. An XMLDocument object can be retrieved from a DOMParser object after an XML document has been parsed. The XMLDocument class provides select methods to select nodes in an XML document with an XPath expression.

In this article we'll parse an example XML document with the DOMParser class, obtain an XMLDocument object for the XML document, and select nodes from the document with the XMLDocument class select methods. The different select methods in the XMLDocument class are discussed in Table 2.

The XML document parsed in this article has a namespace declaration xmlns:journal="http://www.xdk11g.com/xpath" for elements in the namespace with the prefix journal. For an introduction on namespaces in XML refer to the W3C Recommendation on Namespaces in XML 1.0. catalog.xml, the example XML document, is shown in Listing 1.

Setting the Environment
Create an application (called XPath, for example) and a project (called XPath) in JDeveloper. The XPath API will be demonstrated in a Java application. Therefore, create a Java class in the XPath project with File | New. In the New Gallery window, select < >Categories | General and Items | Java Class. In the Create Java Class window, specify the class name (XPathParser, for example), the package name (xpath in the example application), and click on the OK button.

To develop an application with XPath, add the required libraries to the project classpath. Select the project node in Application Navigator and select Tools | Project Properties. In the Project Properties window, select the Libraries and Classpath node. To add a library, select the Add Library button. Select the Oracle XML Parser v2 library. Click on the OK button in the Project Properties window. We also need to add an XML document that is to be parsed and navigated with XPath. To add an XML document, select File | New. In the New Gallery window, select Categories | General | XML and Items | XML Document. Click on the OK button. In the Create XML File window specify the file name catalog.xml in the File Name field, and click on the OK button. Copy the catalog.xml listing to the catalog.xml file in the Application Navigator. The directory structure of the XPath project is shown in Figure 1.

XPath Search
In this section, we'll select nodes from the example XML document, catalog.xml, with the XPath Search tool of JDeveloper 11g. The XPath Search tool consists of an Expression field for specifying an XPath expression. Specify an XPath expression and click on OK to select nodes matching the XPath expression. The XPath Search tool has a provision to search for nodes in a specific namespace. An XML namespace is a collection of element and attribute names that are identified by a URI reference. Namespaces are specified in an XML document using namespace declarations. A namespace declaration is an xmlns-prefixed attribute in an element that consists of a namespace prefix in the attribute name with the namespace URI as the attribute value.

If you want to select nodes in a specific namespace or nodes from different namespaces, first add the namespace Prefix and URI to the XPath Search tool using the Add button. Subsequently, include namespace prefixes in the XPath expression. The XPath Search tool is shown in Figure 2.

To navigate catalog.xml with XPath, select catalog.xml in the Application Navigator and select Search | XPath Search (see Figure 3).

In the following subsections, we'll select example nodes using absolute location paths and relative location paths. Use a relative location path if the XML document is large and a specific node is required. Use a relative path if the node from which subnodes are to be selected and the relative location path are known. Use an absolute location path if the XML document is small, or if the relative location path isn't known. The objective is to use minimum XPath navigation. Use the minimum number nodes to navigate to select the required node.

Selecting Nodes with Absolute Location Paths
Next, we'll demonstrate various examples of selecting nodes using XPath. As an example, select all the title elements in catalog.xml. Specify the XPath expression for selecting the title elements in the Expression field of the Apply an XPath Expression on catalog.xml window. The XPath expression to select all title elements is /catalog/journal/article/title. Click on the OK button to select the title elements (see Figure 4).

The title elements get selected. Title elements from the journal:article elements in the journal namespace don't get selected because a namespace hasn't been applied to the XPath expression (see Figure 5).

As an other example, select the title element in the first article element using the XPath expression /catalog/journal/article[1]/title. We're not using namespaces yet. The XPath expression is specified in the Expression field (see Figure 6).

The title of the first article element gets selected as shown in the JDeveloper output (see Figure 7).

Attribute nodes can also be selected with XPath. Attributes are selected by using the "@" prefix. As an example, select the section attribute in the first article element in the journal element. The XPath expression for selecting the section attribute is /catalog/journal/article[1]/@section and is specified in the Expression field. Click on the OK button to select the section attribute (see Figure 8).

The attribute section gets outputted in JDeveloper:

Applying XPath Expression...
Applying:[/catalog/journal/article[1]/@section] to C:\JDeveloper\mywork\XPath\Xsection="TECHNOLOGY"
Selected 1 node(s) in 0 ms

Selecting Nodes with Relative Location Paths
In the previous examples, an absolute location is used to select nodes. Next, we'll demonstrate selecting an element with a relative location path. As an example, select the title of the first article element in the journal element. The relative location path for selecting the title element is child::catalog/journal/article[position()=1]/title. Specifying the axis as child and node test as catalog selects all the child nodes of the catalog node and is equivalent to an absolute location path that starts with /catalog. If the child nodes of the journal node have to be selected, specify the node test as journal. Specify the XPath expression in the Expression field and click on the OK button (see Figure 9).

The title of the first article element in the journal element gets selected as shown here:

Applying XPath Expression...
Applying:[child::catalog/journal/article[position()=1)/title] to C:\JDeveloper\ms
<title>Oracle Database 11g Redux</title>
Selected 1 node(s) in 0 ms

Selecting Namespace Nodes
XPath Search also has the provision to select elements and attributes in a namespace. To illustrate, select all the title elements in the journal element (that is, in the journal namespace) using the XPath expression /catalog/journal:journal/journal:article/title. First, add the namespaces of the elements and attributes to be selected in the Namespaces text area. The prefix and URI of the namespaces are added with the Add button. Specify the prefix in the Prefix column and the URI in the URI column. Multiple namespace mappings can be added. XPath expressions that select namespace nodes are similar to no-namespace expressions, except that the namespace prefixes are included in the expressions. Elements in the default namespace, which doesn't have a namespace prefix, are also considered to be in a namespace. Click on the OK button to select the nodes with XPath (see Figure 10).

The title elements in the journal element (in the journal namespace) get selected and outputted in JDeveloper:

Applying XPath Expression...
Applying:[/catalog/journal:journal/journal:article/title] to C:\JDeveloper\mywork\XPath\XPath\catalog.xmlwith [http://www.xdk11g.com/xpath] as [journal]
<title>application Server Convergence</title>
Selected 2 node(s) in 0 ms

Attributes in a namespace can be selected with XPath Search. As an example, select the section attributes in the journal namespace. Specify the XPath expression to select the section attributes in the Expression field and click the OK button (see Figure 11).

Section attributes in the journal namespace get selected:

Applying XPath Expression...
Applying:[/catalog/journal:journal/journal:article/@journal:section] to C:\JDeveloper with [http://www.xdk11g.com/xpath] as [journal]
journal:section="ORACLE DEVELOPER"
journal:section="COMMENT"
Selected 2 node(s) in 0 ms

Selecting Nodes with XPath API
In the previous section, XML document nodes were selected automatically with the XPath Search tool in JDeveloper. In this section, we'll select nodes with the XPath API in the XPathParser class. JDeveloper XPath searches with the XPath Search tool are for the convenience of the developer as they find nodes faster than when looking through the XML file. The XPath searches, using the XPath API, actually let your application find nodes via XPath.

The XMLDocument class has select methods to select nodes with an XPath expression. A single node can be selected or a NodeList of nodes can be selected. Nodes declared in a namespace may also be selected. First, we need to import the oracle.xml.parser.v2 package that has the XMLDocument class and the parser class DOMParser from which an XMLDocument can be obtained.

import oracle.xml.parser.v2.*;

Creating the DOM parser
Next we need to parse an XML document and create a DOM structure for the XML document before being able
to select nodes with XPath. Therefore, create a DOMParser using:

DOMParser domParser=new DOMParser();

The DOMParser class that extends the XMLParser class has overloaded the parse methods to parse an XML document from different input sources. An XML document can be parsed from InputSource, InputStream, Reader, String, or URL. In the XPathParser.java example application we'll parse an example document from a FileReader.

Create a FileReader object from a File object and parse it with the parse(Reader) method as shown in the following listing:

domParser.parse(new FileReader(xmlDocument));

The variable xmlDocument is the File representation of the XML document catalog.xml. The class that provides XPath functionality is XMLDocument. Obtain an XMLDocument object from the DOMParser object with the getDocument() method.

XMLDocument document=domParser.getDocument();

Method selectSingleNode(String)
The XMLDocument class method selectSingleNode(String) selects a single node specified by an XPath expression. If more than one node matches the XPath expression, the first node that matches the XPath expression gets selected. As an example, select the title of the first article node with the section attribute value ORACLE DEVELOPER. The title element is selected with the selectSingleNode(String) method as shown here:

XMLNode titleNode=(XMLNode)document.selectSingleNode("/catalog/
journal/article[@section='ORACLE DEVELOPER']/title");

The title element value can be selected by first selecting the text node in the title element node using the getFirstChild() method and subsequently selecting the text node value using the getNodeValue() method, as shown in the following listing:

String title=titleNode.getFirstChild().getNodeValue();

As another example of the selectSingleNode(String) method, select the author of the article with the title Oracle Database 11g Redux, as shown here:

XMLNode authorNode=(XMLNode)document.selectSingleNode("/catalog/
journal/article[title= Oracle Database 11g Redux']/author");

The author element text value is outputted by first selecting the text node in the author element node using the getFirstChild() method and subsequently selecting the text node value using the getNodeValue() method, as shown here:

String author=authorNode.getFirstChild().getNodeValue();

The XMLDocument class selectSingleNode(String) can also be used to select an attribute node. As an example, select the section attribute of the second article in the journal date March-April 2008:

XMLNode sectionNode=(XMLNode)document.selectSingleNode("/catalog/
journal[@date=March-April 2008]/article[2]/@section");

The section node value can be selected with the getNodeValue() method:

String section=sectionNode.getNodeValue();

Method selectNodes(String)
The XMLDocument class method selectNodes(String XPathExpression) selects all the nodes specified by an XPath expression. As an example, select all the title elements for the journal of date March-April 2008, as shown in the following listing:

NodeList nodeList=document.selectNodes("/catalog/journal[@date='March-
April 2008']/article/title");

The method selectNodes(String) returns a NodeList that can be iterated over to output title elements:

for(int i=0; i<nodeList.getLength(); i++){
titleNode=(XMLElement)nodeList.item(i);
title=titleNode.getFirstChild().getNodeValue();
System.out.println(title);
}

The method selectNodes(String) can also be used to select attribute nodes. For example, select all the section attributes for the articles in the journal of date March-April 2008:

NodeList
nodeList=document.selectNodes("/catalog/journal[@date='March- April
2008]/article/@section");

The NodeList of section nodes can be iterated over to output section node values as shown in the following listing:

for(int i=0; i<nodeList.getLength(); i++){
XMLNode sectionNode=(XMLNode)nodeList.item(i);
String section=sectionNode.getNodeValue();
System.out.println(section+" ");
}

Method selectSingleNode(String,NSResolver)
The XMLDocument class method selectSingleNode(String XSLPattern, NSResolver resolver) selects a single node specified by an XPath expression. NSResolver is used to resolve any namespace prefixes that may occur in the XPath expression.

To select nodes in a namespace, create a class - for example, CustomNSResolver - that implements the NSResolver interface. In the implementation class, implement the NSResolver method resolveNamespacePrefix(String prefix) as shown in the following listing:

class CustomNSResolver implements NSResolver{
public java.lang.String resolveNamespacePrefix(java.lang.String
prefix){

if(prefix.equals("journal")){
return new String("http://www.xdk11g.com/xpath");
}
}
}

The resolveNamespacePrefix method accepts a prefix and returns a URI. Create an NSResolver object. Set the namespace prefix to resolve using the resolveNamespacePrefix method:

CustomNSResolver resolver=new CustomNSResolver();
resolver.resolveNamespacePrefix("journal");

In the XML document example, catalog.xml, one of the journal elements is in the journal namespace. As an example, select the section attribute in the journal namespace in the first article element (in journal namespace) in the journal element (in journal namespace). The section attribute value will be outputted with the getNodeValue() method, as shown in the following listing:

XMLNode sectionNode= (XMLNode)document.selectSingleNode("/catalog/
journal:journal/journal:article/@journal:section", resolver);
section=sectionNode.getNodeValue();

As a contrast between the selectSingleNode method that takes an NSResolver and the selectSingleNode method that doesn't, the method that doesn't take an NSResolver doesn't select nodes in a namespace. On the other hand, the one that does selects nodes in a namespace. If the method that doesn't take an NSResolver is invoked with an XPath expression containing namespace nodes, the following error is generated:

XSLException Namespace prefix ‘journal' used but not declared.

Method selectNodes(String,NSResolver)
The XMLDocument class method selectNodes(String XPathExpression, NSResolver resolver) selects all the namespace nodes resolved by an NSResolver that are specified in an XPath expression. NSResolver is used to resolve any prefixes that can occur in the XPath expression. For example, select all the title elements in journal (in journal namespace) of date (in journal namespace) November-December 2008, as shown in this listing:

NodeList nodeList=document.selectNodes("/catalog/journal:journal[@
journal:date='November-December 2008']/journal:article/title",
resolver );

The namespace prefix journal in the XPath expression is resolved with an NSResolver object. The NodeList returned by the selectNodes(String, NSResolver) method can be iterated over to output the title elements.

for(int i=0; i<nodeList.getLength(); i++){
titleNode=(XMLElement)nodeList.item(i);
title=titleNode.getFirstChild().getNodeValue();
System.out.println(title);
}

Running the Java Application
The Java program XPathParser.java is used to select nodes from the XML document catalog.xml. The Java application is listed with additional explanations about the application as follows:

1. First we import the required packages from XDK 11g.

import oracle.xml.parser.v2.*;
import java.io.*;
import org.xml.sax.SAXException;
import org.w3c.dom.*;

2. Next we add the XPathParser Java class declaration.

public class XPathParser{

3. We define the parseDocument method to parse an XML document with the DOMParser

public void parseDocument(File xmlDocument){
try{

4. Next we create a DOMParser object and parse the XML document.

DOMParser domParser=new DOMParser();
domParser.parse(new FileReader(xmlDocument));
XMLDocument document=domParser.getDocument();

5. We specify the NSResolver object to resolve namespaces.

CustomResolver resolver=new CustomResolver();
resolver.resolveNamespacePrefix("journal");

6. Next we select nodes using the selectSingleNode(String) method as shown in Listing 2 below.
7. Then we select nodes using the selectNodes(String) method as shown in Listing 3 below.
8. Next, we select nodes using the selectSingleNode(String, NSResolver) method.

sectionNode=(XMLNode)document.selectSingleNode("/catalog/journal:
journal/journal:article/@journal:section", resolver);


section=sectionNode.getNodeValue();
System.out.println("Section of first article in first journal
(nodes being in journal namespace) is "+section+" ");


System.out.println("Titles for articles in journal of date
November-December 2008 (journal, article, and date nodes being in journal namespace) are ");

9. We also select nodes using the selectNodes(String,NS Resolver) method as shown in Listing 4 below.
10. Then we add the Java class that extends the NSResolver  class.

class CustomResolver implements NSResolver{
public java.lang.String
resolveNamespacePrefix(java.lang.String prefix){
if(prefix.equals("journal")){
return new "http://www.xdk11g.com/xpath";
}else
return null;
}
}

11. Finally, we define the main method in which we create an instance of the XPathParser class and invoke the parseDocument method.

public static void main(String[] argv){
XPathParser parser=new XPathParser();
parser.parseDocument(new File("catalog.xml"));
}
}

To run the XPathParser.java application in JDeveloper, right-click on the XPathParser.java node in the Application Navigator and select Run. The output from the XPathParser.java application is shown in Figure 12.

Summary
You learned about XPath support in JDeveloper 11g. JDeveloper provides an XPath Search GUI tool to select nodes from an XML document using XPath. We selected nodes using absolute location paths and relative location paths, and also selected namespace nodes. We discussed the XDK's XMLDocument class select methods to select elements and attributes in an XML document with XPath. The select methods can be used to select single nodes or collections of nodes. The select methods can also be used to select nodes in a namespace.

More Stories By Deepak Vohra

Deepak Vohra is a Sun Certified Java 1.4 Programmer and a Web developer.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.