What is XPath?

Processing XML documents with Oracle JDeveloper 11g

While a number of books on XML are available, none covers XML support in Oracle JDeveloper. Welcome to Processing XML documents with Oracle JDeveloper 11g, a book that will teach you about using Oracle XML technologies in Oracle JDeveloper. XML is the standard medium of data exchange. Examples of data exchange using XML are web feeds, which include RSS feeds and Atom feeds, and XML messages in web services. Java is the language most commonly used to process XML.

also read:

Among the IDEs, Oracle JDeveloper has the most XML features. Some of the graphical XML features in JDeveloper are an XML editor to create an XML document, an XML schema editor to model an XML schema, and an XPath explorer to process XPath expressions. JDeveloper also provides built-in support for JAXB compilation. JDeveloper includes an integrated application server—the WebLogic Server—for running XML-based applications. Oracle XML Developer Kit (XDK) provides a set of components, tools, and utilities for developing XML-based applications. The XDK 11g libraries are included with Oracle JDeveloper 11g.

The objective of this book is to discuss XML development in Oracle JDeveloper. We shall use JDeveloper 11g, the latest version of JDeveloper. As developers commonly use an IDE for processing XML and developing XML applications, the book covers all aspects of XML development, which include:

  • Creating an XML document
  • Validating an XML document with an XML schema
  • Transforming an XML document
  • Addressing elements/attributes in an XML document using XPath

We shall use the Oracle XDK 11g for Java to develop XML applications. We shall also discuss Oracle XML Publisher and Oracle Berkeley DB XML. By the end of this book, you should know everything there is to know about XML and JDeveloper.

What This Book Covers

Chapter 1: We discuss creating an XML document using Oracle’s XML Developer Kit (XDK) 11g in Oracle JDeveloper. We also discuss parsing an XML document using SAX and DOM Java APIs, which are also included in XDK 11g.

Chapter 2: We create an XML schema in the XML schema editor of Oracle JDeveloper. An XML schema represents the structure of an XML document. Subsequently, we instantiate an XML document from the XML schema.

Chapter 3: We discuss validating an XML document with an XML schema using the built-in feature to validate the schema and the XDK 11g schema validation APIs. We discuss three different APIs for schema validation: the XSDValidator, the SAX parser, and the DOM parser.

Chapter 4: We discuss XPath, which is used to address nodes in an XML document. We use XPath in the XPath Search GUI tool in Oracle JDeveloper 11g. We also use the XPath Java API in XDK 11g.

Chapter 5: We transform an XML document using the Transformation API for XML (TrAX), which is included in XDK 11g. We also discuss the XSLT extension functions.

Chapter 6: We parse and transform XML using the JSTL XML tag library in JDeveloper 11g.

Chapter 7: We load, save, and filter an XML document using the DOM 3.0 Load and Save APIs, which are provided in XDK 11g.

Chapter 8: We construct and validate an XML document using the DOM 3.0 Validation API, which is also included in XDK 11g.

Chapter 2: We discuss another built-in feature of JDeveloper 11g, the JAXB 2.0 compiler. We bind an XML schema to Java classes using the JAXB 2.0 compiler. Subsequently, we unmarshal an XML document and marshal an XML document using the compiled Java classes.

Chapter 10: We compare XML documents using the XMLDiff Java API included in XDK 11g.

Chapter 11: We convert an XML document to a PDF document using the Apache FOP Java API in JDeveloper.

Chapter 12: We create an MS Excel spreadsheet from an XML document in JDeveloper using the Apache POI Java API.

Chapter 13: We store an XML document in Oracle Berkeley DB XML, and subsequently query and update the XML document using both the Berkeley DB XML command shell and the Berkeley DB XML Java API. The Berkeley DB XML API is used in JDeveloper 11g.

Chapter 14: We create PDF reports in JDeveloper 11g using the Oracle XML Publisher Java API. We also merge PDF documents. We also create an XML report from a database table using the Data Engine API.

What is XPath?

As mentioned in the earlier chapters, XML documents can be used for the transfer of data. The data in an XML document may 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 that a single node may be selected directly without iterating over a node set. With SAX and DOM APIs, node lists have to be iterated over 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. In this chapter we shall discuss XPath support in JDeveloper.

What is XPath?

XPath is a language for addressing an XML document’s elements and attributes. As an example, say you receive an XML document that contains the details of a shipment and you want to retrieve the element/attribute values from the XML document. You don’t just want to list the values of all the nodes, but also want to output the values of specific elements or attributes. In such a case, you would use
XPath to retrieve the values of those elements and attributes. XPath constructs a hierarchical structure of an XML document, a tree of nodes, which is 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 the following table:

NodeType Description
Root NodeThe root node is the root of the DOM tree. The document element
(the root element) is a child of the root node. The root node also
has the processing instructions and comments as child nodes.
Element NodeThis represents an element in an XML document. The character
data, elements, processing instructions, and comments within an
element are the child nodes of the element node.
Attribute NodeThis represents an attribute other than the xmlns-prefixed
attribute, which declares a namespace.
Text NodeThe character data within an element is a text node. A text
node has at least one character of data. A whitespace is also
considered as a character of data. By default, the ignorable
whitespace after the end of an element and before the start of the
following element is also a text node. The ignorable whitespace
can be excluded from the DOM tree built by parsing an XML
document. This can be done by setting the whitespace-preserving
mode to false with the setPreserveWhitespace(boolean
flag) method.
Comment NodeThis represents a comment in an XML document, except the
comments within the DOCTYPE declaration.
Processing Instruction NodeThis represents a processing instruction in an XML document
except the processing instruction within the DOCTYPE
declaration. The XML declaration is not considered as a
processing instruction node.
Namespace NodeThis represents a namespace mapping, which consists of a
xmlns:-prefixed attribute such as xmlns:xsd=”http://www.
w3.org/2001/XMLSchema”. A namespace node consists of a
namespace prefix (xsd in the example) and a namespace URI
(http://www.w3.org/2001/XMLSchema in the example).

Specific nodes including element, attribute, and text nodes may 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 on XPath refer to the W3C Recommendation for
XPath
(http://www.w3.org/TR/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 the example, the child axis contains the child nodes of the context node. Node test is the journal node set, and 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 support in Oracle XDK 11g

As we discussed in Chapter 1, 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 may 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 chapter we shall 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 the following table:

Method NameDescription
selectSingleNode(String
XPathExpression)
Selects a single node that matches an XPath expression.
If more than one node matches the specified
expression, the first node is selected. Use this method
if you want to select the first node that matches an
XPath expression.
selectNodes(String
XPathExpression)
Selects a node list of nodes that match a specified
XPath expression. Use this method if you want to select
a collection of similar nodes.
selectSingleNode(String
XPathExpression,
NSResolver resolver)
Selects a single namespace node that matches a
specified XPath expression. Use this method if the XML
document has nodes in namespaces and you want to
select the first node that is in a namespace and matches
an XPath expression.
selectNodes(String
XPathExpression,
NSResolver resolver)
Selects a node list of nodes that match a specified
XPath expression. Use this method if you want to select
a collection of similar nodes that are in a namespace.

The example XML document that is parsed in this chapter has a namespace declaration mlns: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 (http://www.w3.org/ TR/REC-xml-names/). catalog.xml, the example XML document, is shown in the
following listing:

<?xml version="1.0" encoding="UTF-8"?>
<catalog xmlns:journal="http://www.xdk11g.com/xpath"
		title="Oracle Magazine" publisher="Oracle Publishing">
   <journal:journal journal:date="November-December 2008">
	  <journal:article journal:section="ORACLE DEVELOPER">
		 <title>Instant ODP.NET Deployment</title>
		 <author>Mark A. Williams</author>
	  </journal:article>
	  <journal:article journal:section="COMMENT">
		 <title>Application Server Convergence</title>
		 <author>David Baum</author>
	  </journal:article>
   </journal:journal>
   <journal date="March-April 2008">
	  <article section="TECHNOLOGY">
		 <title>Oracle Database 11g Redux</title>
		 <author>Tom Kyte</author>
	  </article>
	  <article section="ORACLE DEVELOPER">
		 <title>Declarative Data Filtering</title>
		 <author>Steve Muench</author>
	  </article>
   </journal>
</catalog>

Setting the environment

Create an application (called XPath, for example) and a project (called XPath) in JDeveloper as explained in the earlier chapters. 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 the following illustration:

xpath-1

XPath search

In this section, we shall 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 the 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 here:

xpath-2

To navigate catalog.xml with XPath, select catalog.xml in the Application Navigator and select Search|XPath Search.

xpath-3

In the following subsections, we shall 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. Also, 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 is not known. The objective is to use minimum XPath navigation. Use the minimum number nodes to navigate in order to select the required node.

Selecting nodes with absolute location paths

Nex t, we shall demonstrate with 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.

xpath-4

The title elements get selected. Title elements from the journal:article elements in the journal namespace do not get selected because a namespace has not been applied to the XPath expression.

xpath-5

As an other example, select the title element in the first article element using the XPath expression /catalog/journal/article[1]/title. We are not using namespaces yet. The XPath expression is specified in the Expression field.

xpath-6

The title of the first article element gets selected as shown in the JDeveloper output:

xpath-7

Attribu te nodes may 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.

xpath-8

The attr ibute section gets outputted in JDeveloper.

xpath-9

Selecting nodes with relative location paths

In the pr evious examples, an absolute location is used to select nodes. Next, we shall 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 were required to be selected, specify the node test as journal. Specify the XPath expression in the Expression
field and click on the OK button.

xpath-10

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

xpath-11

Selecting namespace nodes

XPath Searc h 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. Prefix and URI of namespaces are added with the Add button. Specify the prefix in the Prefix column, and the URI in the URI column. Multiple namespace mappings may 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 does not have a namespace prefix, are also considered to be in a namespace. Click on the OK button to select the nodes with XPath.

xpath-12

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

Attributes in a namespace may also 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 on the OK button.

Section attributes in the journal namespace get selected.

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 shall 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 may be selected or a NodeList of nodes may 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 may be obtained.

	import oracle.xml.parser.v2.*;

Creating the DOM parser

Next, we need t o 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, which extends the XMLParser class, has overloaded the parse methods to parse an XML document from different input sources. An XML document may be parsed from InputSource, InputStream, Reader, String, or URL. In the example application XPathParser.java, we shall 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));

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 selectS ingleNode(String)

The XMLDocument class method selectSingleNode(String) selects a single node specified by an XPath expression. If more than one nodes match 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 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 may 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 within 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) may also be used to select an attribute node. As an example, select the section attribute of the second article in the journal of date March-April 2008:

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

The section node value may 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 may 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) may 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 may 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 example XML document, 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 b etween the selectSingleNode method that takes an NSResolver and the selectSingleNode method that doesn’t, the method that doesn’t take an NSResolver does not select nodes in a namespace. On the other hand, the one thatdoes selects nodes in a namespace. If the method that does not 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 may 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 the following 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 may 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 progra m 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.
  4. 	public void parseDocument(File xmlDocument){
    	   try{
    
  5. Next, we create a DOMParser object and parse the XML document.
    	DOMParser domParser=new DOMParser();
    	domParser.parse(new FileReader(xmlDocument));
    	XMLDocument document=domParser.getDocument();
    
  6. We specify the NSResolver object to resolve namespaces.
    	CustomResolver resolver=new CustomResolver();
    	resolver.resolveNamespacePrefix("journal");
    
  7. Next, we select nodes using the selectSingleNode(String) method.
    	XMLNodetitleNode=(XMLNode)document.selectSingleNode
    	("/catalog/journal/article[@section=' ORACLE DEVELOPER']/title");
    	String title=titleNode.getFirstChild().getNodeValue();
    	System.out.println("Title of first Article in ORACLE DEVELOPER
    	Section (with nodes not in any namespace) is "+ title);
    	XMLNode authorNode=(XMLNode)document.selectSingleNode("/catalog/
    	journal/article[title= Oracle Database 11g Redux']/author");
    	String author=authorNode.getFirstChild().getNodeValue();
    	   System.out.println("Author of Title Oracle Database 11g Redux
    	   is "+ author);
    	   XMLNode sectionNode=(XMLNode)document.selectSingleNode
    	   ("/catalog/journal[@date=March-April 2008']/article[2]
    	   /@section");
    	String section=sectionNode.getNodeValue();
    	System.out. println("Section of 2nd Article in Journal of date
    	March-April 2008 is "+ section);
    
  8. We select nodes using the selectNodes(String) method.
    	NodeList nodeList = document.selectNodes("/catalog/journal[@date=
    	'March-April 2008']/article/title");
    	System.out.println("Article Titles published in journal of March-
    	April 2008 are: ");
    	for(int i=0; i<nodeList.getLength(); i++){
    	   titleNode=(XMLElement)nodeList.item(i);
    	   title=titleNode.getFirstChild().getNodeValue();
    	   System.out.println(title);
    	}
    	nodeList=document.selectNodes("/catalog/journal[@date='March-April
    	2008']/article/@section");
    	System.out.println("Articles in journal of March-April 2008 were
    	published in Sections: ");
    	for(int i=0; i<nodeList.getLength(); i++){
    	   sectionNode=(XMLNode)nodeList.item(i);
    	   section=sectionNode.getNodeValue();
    	   System.out.println(section+" ");
    	}
    
  9. 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 ");
    
  10. We also select nodes using the selectNodes(String,NSResolver) method.
    	nodeList=document.selectNodes("/catalog/journal:journal[@journal:
    	date= 'November-December 2008']/journal:article/title",
    	resolver );
    	for(int i=0; i<nodeList.getLength(); i++){
    	   titleNode=(XMLElement)nodeList.item(i);
    	   title=titleNode.getFirstChild().getNodeValue();
    	   System.out.println(title);
    	   }
    	   }catch(IOException e){
    	      System.err.println("IOException"+e.getMessage());
    	   }
    	   catch(XMLDOMException e){
    	      System.err.println("XMLDOMException"+e.getMessage());
    	   }
    	   catch(XMLParseException e)
    	      {System.err.println("XMLParseException"+e.getMessage());
    	   }
    	   catch(XSLException e){
    	      System.err.println("XSLException"+e.getMessage());
    	   }
    	   catch(SAXException e){
    	      System.err.println("SAXException"+e.getMessage());
    	   }
    	}
    
  11. 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;
    	   }
    	}
    
  12. 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 the following illustration:

Summary

In this chapter 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 may be used to select single nodes or collections of nodes. The select methods may also be used to select nodes in a namespace. In the next chapter, you will learn about XSLT(Extensible Stylesheet Language Transformation) support in JDeveloper.

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*