<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>JavaBeat &#187; XML</title>
	<atom:link href="http://www.javabeat.net/category/xml-web-services/xml/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.javabeat.net</link>
	<description>Java Technology News</description>
	<lastBuildDate>Fri, 24 May 2013 01:32:07 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Generate XSD from XML files</title>
		<link>http://www.javabeat.net/2012/04/generate-xsd-from-xml-files/</link>
		<comments>http://www.javabeat.net/2012/04/generate-xsd-from-xml-files/#comments</comments>
		<pubDate>Thu, 12 Apr 2012 06:09:26 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[XML]]></category>
		<category><![CDATA[XSD]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=1028</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>XSD is the XML schema definition for defining the XML elements in the XML document. Prior to the XML schemas, DTDs are used which are not XML document and has the limitations. XSD is most popular because of the extensibility and the validations for the XML files. You can set the validation rules for the [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><a id="dd_start"></a><p>XSD is the XML schema definition for defining the XML elements in the XML document. Prior to the XML schemas, DTDs are used which are not XML document and has the limitations. XSD is most popular because of the extensibility and the validations for the XML files. You can set the validation rules for the XML files and the values in the XML documents can be validated using the XSD documents. There are number of tools available in the internet to perform the validation tasks.</p>
<p>There are times when developer wants to generate the XSD from the XML files. In a typical scenario, XSD is written seperately without referring the XML document because XML data can be wrong. In case, if you don&#8217;t have the XSD for an XML document and want to generate the XSD for that XML document, there are tools in the internet. This article is not to explain much detail on how to generate the XSD from XML, but to give an idea on where to get the details on the tools and guiding for the resources on the internet.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<ul>
<li><a href="http://www.ehow.com/how_6907958_convert-xml-xsd-online.html" target="_blank">How to Convert XML to Xsd Online</a></li>
<li><a href="http://www.ehow.com/how_6907958_convert-xml-xsd-online.html" target="_blank">XML-2-XSD</a></li>
<li><a href="http://stackoverflow.com/questions/288236/xsd-code-generator" target="_blank">List of Links</a></li>
</ul>
<p>If you are facing any issues on converting the XML files into the XSD, please post it here.</p>
<div class='dd_outer'><div class='dd_inner'><div id='dd_ajax_float'><div class='dd_button_v'><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="http%3A%2F%2Fwww.javabeat.net%2Fcategory%2Fxml-web-services%2Fxml%2Ffeed%2F" send="false" show_faces="false"  layout="box_count" width="50"  ></fb:like></div><div style='clear:left'></div><div class='dd_button_v'><script type='text/javascript' src='https://apis.google.com/js/plusone.js'></script><g:plusone size='tall' href='http://www.javabeat.net/category/xml-web-services/xml/feed/'></g:plusone></div><div style='clear:left'></div><div class='dd_button_v'><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.javabeat.net/category/xml-web-services/xml/feed/" data-count="vertical" data-text="XML" data-via="javabeat" ></a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div style='clear:left'></div><div class='dd_button_extra_v'><script type="text/javascript">jQuery(document).load(function(){ stLight.options({publisher:'bab47279-62c9-46af-addc-79fd1fe8fee0'}); });</script><div class="st_email_custom"><span id='dd_email_text'>email</span></div></div><div style='clear:left'></div><div class='dd_button_extra_v'><div id='dd_print_button'><span id='dd_print_text'><a href='javascript:window:print()'>print</a></span></div></div><div style='clear:left'></div></div></div></div><script type="text/javascript">var dd_offset_from_content = 44; var dd_top_offset_from_content = 0;</script><script type="text/javascript" src="http://www.javabeat.net/wp-content/plugins/digg-digg//js/diggdigg-floating-bar.js?ver=5.3.0"></script><div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/04/generate-xsd-from-xml-files/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What is XPath?</title>
		<link>http://www.javabeat.net/2009/04/what-is-xpath/</link>
		<comments>http://www.javabeat.net/2009/04/what-is-xpath/#comments</comments>
		<pubDate>Fri, 03 Apr 2009 14:54:47 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=2225</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>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 [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><strong>Processing XML documents with Oracle JDeveloper 11g</strong></p>
<p>While a number of books on XML are available, none covers XML support in Oracle JDeveloper. Welcome to <i>Processing XML documents with Oracle JDeveloper 11g</i>, 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.</p>
<p>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 <b>XML Developer Kit (XDK)</b> provides a set of components, tools, and utilities for developing XML-based applications. The XDK 11g libraries are included with Oracle JDeveloper 11g.</p>
<p>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:</p>
<ul>
<li>Creating an XML document</li>
<li>Validating an XML document with an XML schema</li>
<li>Transforming an XML document</li>
<li>Addressing elements/attributes in an XML document using XPath</li>
</ul>
<p>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.</p>
<p><strong>What This Book Covers</strong></p>
<p><i>Chapter 1</i>: We discuss creating an XML document using Oracle&#8217;s <b>XML Developer Kit (XDK)</b> 11g in Oracle JDeveloper. We also discuss parsing an XML document using SAX and DOM Java APIs, which are also included in XDK 11g.</p>
<p><i>Chapter 2</i>: 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.</p>
<p><i>Chapter 3</i>: 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.</p>
<p><i>Chapter 4</i>: 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.</p>
<p><i>Chapter 5</i>: 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.</p>
<p><i>Chapter 6</i>: We parse and transform XML using the JSTL XML tag library in JDeveloper 11g.</p>
<p><i>Chapter 7</i>: We load, save, and filter an XML document using the DOM 3.0 Load and Save APIs, which are provided in XDK 11g.</p>
<p><i>Chapter 8</i>: We construct and validate an XML document using the DOM 3.0 Validation API, which is also included in XDK 11g.</p>
<p><i>Chapter 2</i>: 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.</p>
<p><i>Chapter 10</i>: We compare XML documents using the XMLDiff Java API included in XDK 11g.</p>
<p><i>Chapter 11</i>: We convert an XML document to a PDF document using the Apache FOP Java API in JDeveloper.</p>
<p><i>Chapter 12</i>: We create an MS Excel spreadsheet from an XML document in JDeveloper using the Apache POI Java API.</p>
<p><i>Chapter 13</i>: 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.</p>
<p><i>Chapter 14</i>: 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.</p>
<h2 style="text-align: center;"><span style="text-decoration: underline;"><span style="color: #000080; text-decoration: underline;">What is XPath?</span></span></h2>
<p>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 <b>JAXP (Java API for XML Processing)</b> DOM and SAX APIs, or with the JAXP XPath API. Addressing<br />
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.</p>
<h2>What is XPath?</h2>
<p>XPath is a language for addressing an XML document&#8217;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&#8217;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<br />
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:</p>
<table border="1">
<tbody>
<tr>
<th>Node</th>
<th>Type Description</th>
</tr>
<tr>
<td>Root Node</td>
<td>The root node is the root of the DOM tree. The document element<br />
(the root element) is a child of the root node. The root node also<br />
has the processing instructions and comments as child nodes.</td>
</tr>
<tr>
<td>Element Node</td>
<td>This represents an element in an XML document. The character<br />
data, elements, processing instructions, and comments within an<br />
element are the child nodes of the element node.</td>
</tr>
<tr>
<td>Attribute Node</td>
<td>This represents an attribute other than the xmlns-prefixed<br />
attribute, which declares a namespace.</td>
</tr>
<tr>
<td>Text Node</td>
<td>The character data within an element is a text node. A text<br />
node has at least one character of data. A whitespace is also<br />
considered as a character of data. By default, the ignorable<br />
whitespace after the end of an element and before the start of the<br />
following element is also a text node. The ignorable whitespace<br />
can be excluded from the DOM tree built by parsing an XML<br />
document. This can be done by setting the whitespace-preserving<br />
mode to false with the setPreserveWhitespace(boolean<br />
flag) method.</td>
</tr>
<tr>
<td>Comment Node</td>
<td>This represents a comment in an XML document, except the<br />
comments within the DOCTYPE declaration.</td>
</tr>
<tr>
<td>Processing Instruction Node</td>
<td>This represents a processing instruction in an XML document<br />
except the processing instruction within the DOCTYPE<br />
declaration. The XML declaration is not considered as a<br />
processing instruction node.</td>
</tr>
<tr>
<td>Namespace Node</td>
<td>This represents a namespace mapping, which consists of a<br />
xmlns:-prefixed attribute such as xmlns:xsd=&#8221;http://www.<br />
w3.org/2001/XMLSchema&#8221;. A namespace node consists of a<br />
namespace prefix (xsd in the example) and a namespace URI<br />
(http://www.w3.org/2001/XMLSchema in the example).</td>
</tr>
</tbody>
</table>
<p>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.</p>
<pre class="brush: java; title: ; notranslate">	For an introduction on XPath refer to the &lt;i&gt;W3C Recommendation for
	XPath&lt;/i&gt; (http://www.w3.org/TR/xpath). As a brief review,
	expression evaluation in XPath is performed with respect to a &lt;b&gt;context
	node&lt;/b&gt;. The most commonly used type of expression in XPath is a &lt;b&gt;location
	path&lt;/b&gt; . XPath defines two types of location paths: &lt;b&gt;relative location paths&lt;/b&gt;
	and &lt;b&gt;absolute location paths&lt;/b&gt;. 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 &quot;/&quot;. A &lt;b&gt;location step&lt;/b&gt; consists of an &lt;b&gt;axis&lt;/b&gt;, a
	&lt;b&gt;node test&lt;/b&gt;, and &lt;b&gt;predicates&lt;/b&gt;.
</pre>
<p>An example of a location step is:</p>
<pre class="brush: java; title: ; notranslate">	child::journal[position()=2]
</pre>
<p>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 &#8220;/&#8221;. 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 &#8220;/&#8221;.</p>
<h2>XPath support in Oracle XDK 11g</h2>
<p>As we discussed in Chapter 1, Oracle XML Developer&#8217;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.</p>
<p>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:</p>
<table border="1">
<tbody>
<tr>
<th>Method Name</th>
<th>Description</th>
</tr>
<tr>
<td>selectSingleNode(String<br />
XPathExpression)</td>
<td>Selects a single node that matches an XPath expression.<br />
If more than one node matches the specified<br />
expression, the first node is selected. Use this method<br />
if you want to select the first node that matches an<br />
XPath expression.</td>
</tr>
<tr>
<td>selectNodes(String<br />
XPathExpression)</td>
<td>Selects a node list of nodes that match a specified<br />
XPath expression. Use this method if you want to select<br />
a collection of similar nodes.</td>
</tr>
<tr>
<td>selectSingleNode(String<br />
XPathExpression,<br />
NSResolver resolver)</td>
<td>Selects a single namespace node that matches a<br />
specified XPath expression. Use this method if the XML<br />
document has nodes in namespaces and you want to<br />
select the first node that is in a namespace and matches<br />
an XPath expression.</td>
</tr>
<tr>
<td>selectNodes(String<br />
XPathExpression,<br />
NSResolver resolver)</td>
<td>Selects a node list of nodes that match a specified<br />
XPath expression. Use this method if you want to select<br />
a collection of similar nodes that are in a namespace.</td>
</tr>
</tbody>
</table>
<p>The example XML document that is parsed in this chapter has a namespace declaration mlns:journal=&#8221;http://www.xdk11g.com/xpath&#8221; for elements in the namespace with the prefix journal. For an introduction on namespaces in XML refer to the <i>W3C Recommendation on Namespaces in XML 1.0</i> (http://www.w3.org/ TR/REC-xml-names/). catalog.xml, the example XML document, is shown in the<br />
following listing:</p>
<pre class="brush: java; title: ; notranslate">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;catalog xmlns:journal=&quot;http://www.xdk11g.com/xpath&quot;
		title=&quot;Oracle Magazine&quot; publisher=&quot;Oracle Publishing&quot;&gt;
   &lt;journal:journal journal:date=&quot;November-December 2008&quot;&gt;
	  &lt;journal:article journal:section=&quot;ORACLE DEVELOPER&quot;&gt;
		 &lt;title&gt;Instant ODP.NET Deployment&lt;/title&gt;
		 &lt;author&gt;Mark A. Williams&lt;/author&gt;
	  &lt;/journal:article&gt;
	  &lt;journal:article journal:section=&quot;COMMENT&quot;&gt;
		 &lt;title&gt;Application Server Convergence&lt;/title&gt;
		 &lt;author&gt;David Baum&lt;/author&gt;
	  &lt;/journal:article&gt;
   &lt;/journal:journal&gt;
   &lt;journal date=&quot;March-April 2008&quot;&gt;
	  &lt;article section=&quot;TECHNOLOGY&quot;&gt;
		 &lt;title&gt;Oracle Database 11g Redux&lt;/title&gt;
		 &lt;author&gt;Tom Kyte&lt;/author&gt;
	  &lt;/article&gt;
	  &lt;article section=&quot;ORACLE DEVELOPER&quot;&gt;
		 &lt;title&gt;Declarative Data Filtering&lt;/title&gt;
		 &lt;author&gt;Steve Muench&lt;/author&gt;
	  &lt;/article&gt;
   &lt;/journal&gt;
&lt;/catalog&gt;
</pre>
<h2>Setting the environment</h2>
<p>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 <b>File|New</b>. In the <b>New Gallery</b> window select <b>Categories|General </b>and Items|Java Class. In the Create Java Class window, specify the class name<br />
(<b>XPathParser</b>, for example), the package name (<b>xpath</b> in the example application), and click on the <b>OK</b> button.</p>
<p>To develop an application with XPath, add the required libraries to the project classpath. Select the project node in <b>Application Navigator</b> and select <b>Tools|Project Properties</b>. In the <b>Project Properties</b> window, select the <b>Libraries and Classpath</b><br />
node. To add a library, select the <b>Add Library</b> button. Select the <b>Oracle XML Parser v2</b> library. Click on the <b>OK</b> button in the <b>Project Properties</b> window. We also need to add an XML document that is to be parsed and navigated with XPath.</p>
<p>To add an XML document, select <b>File|New</b>. In the <b>New Gallery</b> window, select <b>Categories|General|XML</b> and <b>Items|XML Document</b>. Click on the <b>OK</b> button. In the <b>Create XML File</b> window specify the file name catalog.xml in the <b>File Name </b>field, and click on the <b>OK</b> button. Copy the catalog.xml listing to the <b>catalog.xml </b>file in the <b>Application Navigator</b>. The directory structure of the XPath project is shown in the following illustration:</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-1.bmp"><img class="aligncenter size-full wp-image-6697" alt="xpath-1" src="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-1.bmp" /></a></p>
<h2>XPath search</h2>
<p>In this section, we shall select nodes from the example XML document, catalog.xml, with the <b>XPath Search</b> tool of JDeveloper 11g. The <b>XPath Search</b> tool consists of an <b>Expression</b> field for specifying an XPath expression. Specify an XPath expression and click on <b>OK</b> to select nodes matching the XPath expression. The <b>XPath Search</b> 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<br />
that consists of a namespace prefix in the attribute name with the namespace URI as the attribute value.</p>
<p>If you want to select nodes in a specific namespace or nodes from different namespaces, first add the namespace <b>Prefix</b> and <b>URI</b> to the <b>XPath Search</b> tool using the <b>Add</b> button. Subsequently, include namespace prefixes in the XPath expression. The <b>XPath Search</b> tool is shown here:</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-2.bmp"><img class="aligncenter size-full wp-image-6698" alt="xpath-2" src="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-2.bmp" /></a></p>
<p>To navigate catalog.xml with XPath, select catalog.xml in the Application Navigator and select Search|XPath Search.</p>
<p style="text-align: center;"><a href="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-3.bmp"><img class="aligncenter  wp-image-6699" alt="xpath-3" src="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-3.bmp" width="466" height="291" /></a></p>
<p>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.</p>
<h2>Selecting nodes with absolute location paths</h2>
<p>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 <b>Expression</b> field of the <b>Apply an XPath Expression on catalog.xml</b> window. The XPath expression to select all title elements is <b>/catalog/journal/article/title</b>. Click on the <b>OK</b> button to select the title elements.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-4.bmp"><img class="aligncenter size-full wp-image-6700" alt="xpath-4" src="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-4.bmp" /></a></p>
<p>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.</p>
<p style="text-align: center;"><a href="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-5.bmp"><img class="aligncenter  wp-image-6701" alt="xpath-5" src="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-5.bmp" width="374" height="215" /></a></p>
<p>As an other example, select the title element in the first article element using the XPath expression /<b>catalog/journal/article[1]/title</b>. We are not using namespaces yet. The XPath expression is specified in the <b>Expression</b> field.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p><a href="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-6.bmp"><img class="aligncenter size-full wp-image-6702" alt="xpath-6" src="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-6.bmp" /></a></p>
<p>The title of the first article element gets selected as shown in the JDeveloper output:</p>
<p style="text-align: center;"><a href="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-7.bmp"><img class="aligncenter  wp-image-6703" alt="xpath-7" src="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-7.bmp" width="376" height="230" /></a></p>
<p>Attribu te nodes may also be selected with XPath. Attributes are selected by using the &#8221;@&#8221; 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<br />
<b>/catalog/journal/article[1]/@section</b> and is specified in the <b>Expression field</b>. Click on the <b>OK</b> button to select the section attribute.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-8.bmp"><img class="aligncenter size-full wp-image-6704" alt="xpath-8" src="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-8.bmp" /></a></p>
<p>The attr ibute section gets outputted in JDeveloper.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-9.bmp"><img class="aligncenter size-full wp-image-6705" alt="xpath-9" src="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-9.bmp" /></a></p>
<h2>Selecting nodes with relative location paths</h2>
<p>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 <b>child::catalog/journal/article[position()=1]/ title</b>. 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 <b>Expression</b><br />
field and click on the <b>OK</b> button.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-10.bmp"><img class="aligncenter size-full wp-image-6706" alt="xpath-10" src="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-10.bmp" /></a></p>
<p>The title of the first article element in the journal element gets selected as shown here:</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-11.bmp"><img class="aligncenter size-full wp-image-6707" alt="xpath-11" src="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-11.bmp" /></a></p>
<h2>Selecting namespace nodes</h2>
<p>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 <b>/catalog/journal:journal/journal:<br />
article/title</b>. First, add the namespaces of the elements and attributes to be selected in the <b>Namespaces</b> text area. Prefix and URI of namespaces are added with the <b>Add</b> button. Specify the prefix in the <b>Prefix</b> column, and the URI in the <b>URI </b>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 <b>OK</b> button to select the nodes with XPath.</p>
<p style="text-align: center;"><a href="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-12.bmp"><img class="aligncenter  wp-image-6708" alt="xpath-12" src="http://www.javabeat.net/wp-content/uploads/2009/04/xpath-12.bmp" width="435" height="275" /></a></p>
<p>The title elements in the journal element (in the journal namespace) get selected and outputted in JDeveloper.</p>
<p>Attributes in a namespace may also be selected with <b>XPath Search</b>. As an example, select the section attributes in the journal namespace. Specify the XPath expression to select the section attributes in the <b>Expression</b> field and click on the <b>OK</b> button.</p>
<p>Section attributes in the journal namespace get selected.</p>
<h2>Selecting nodes with XPath API</h2>
<p>In the previous section, XML document nodes were selected automatically with the <b>XPath Search</b> tool in JDeveloper. In this section, we shall select nodes with the XPath API in the <b>XPathParser</b> 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.</p>
<p>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.</p>
<pre class="brush: java; title: ; notranslate">	import oracle.xml.parser.v2.*;
</pre>
<h2>Creating the DOM parser</h2>
<p>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:</p>
<pre class="brush: java; title: ; notranslate">	DOMParser domParser=new DOMParser();</pre>
<p>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.</p>
<p>Create a FileReader object from a File object and parse it with the parse(Reader) method as shown in the following listing:</p>
<pre class="brush: java; title: ; notranslate">	domParser.parse(new FileReader(xmlDocument));</pre>
<p>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.</p>
<pre class="brush: java; title: ; notranslate">	XMLDocument document=domParser.getDocument();</pre>
<h2>Method selectS ingleNode(String)</h2>
<p>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:</p>
<pre class="brush: java; title: ; notranslate">	XMLNode titleNode=(XMLNode)document.selectSingleNode(&quot;/catalog/
	journal/article[@section='ORACLE DEVELOPER']/title&quot;);
</pre>
<p>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:</p>
<pre class="brush: java; title: ; notranslate">	String title=titleNode.getFirstChild().getNodeValue();
</pre>
<p>As another example of the selectSingleNode(String) method, select the author of the article with the title Oracle Database 11g Redux, as shown here:</p>
<pre class="brush: java; title: ; notranslate">	XMLNode authorNode=(XMLNode)document.selectSingleNode(&quot;/catalog/
	journal/article[title= Oracle Database 11g Redux']/author&quot;);
</pre>
<p>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:</p>
<pre class="brush: java; title: ; notranslate">	String author=authorNode.getFirstChild().getNodeValue();
</pre>
<p>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:</p>
<pre class="brush: java; title: ; notranslate">	XMLNode sectionNode=(XMLNode)document.selectSingleNode(&quot;/catalog/
	journal[@date=March-April 2008]/article[2]/@section&quot;);
</pre>
<p>The section node value may be selected with the getNodeValue() method:</p>
<pre class="brush: java; title: ; notranslate">	String section=sectionNode.getNodeValue();
</pre>
<p>Method selectNodes(String)</p>
<p>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:</p>
<pre class="brush: java; title: ; notranslate">	NodeList nodeList=document.selectNodes(&quot;/catalog/journal[@date='March-
	April 2008']/article/title&quot;);
</pre>
<p>The method selectNodes(String) returns a NodeList that may be iterated over to output title elements:</p>
<pre class="brush: java; title: ; notranslate">	for(int i=0; i&lt;nodeList.getLength(); i++){
	   titleNode=(XMLElement)nodeList.item(i);
	   title=titleNode.getFirstChild().getNodeValue();
	   System.out.println(title);
	}
</pre>
<p>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:</p>
<pre class="brush: java; title: ; notranslate">	NodeList
	nodeList=document.selectNodes(&quot;/catalog/journal[@date='March- April
	2008]/article/@section&quot;);
</pre>
<p>The NodeList of section nodes may be iterated over to output section node values as shown in the following listing:</p>
<pre class="brush: java; title: ; notranslate">	for(int i=0; i&lt;nodeList.getLength(); i++){
	   XMLNode sectionNode=(XMLNode)nodeList.item(i);
	   String section=sectionNode.getNodeValue();
	   System.out.println(section+&quot; &quot;);
	}
</pre>
<h2>Method selectSingleNode(String,NSResolver)</h2>
<p>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.</p>
<p>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:</p>
<pre class="brush: java; title: ; notranslate">	class CustomNSResolver implements NSResolver{
	   public java.lang.String resolveNamespacePrefix(java.lang.String
	   prefix){
	      if(prefix.equals(&quot;journal&quot;)){
		 return new String(&quot;http://www.xdk11g.com/xpath&quot;);
	      }
	   }
	}
</pre>
<p>The resolveNamespacePrefix method accepts a prefix and returns a URI.Create an NSResolver object. Set the namespace prefix to resolve using the resolveNamespacePrefix method:</p>
<pre class="brush: java; title: ; notranslate">	CustomNSResolver resolver=new CustomNSResolver();
	resolver.resolveNamespacePrefix(&quot;journal&quot;);
</pre>
<p>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:</p>
<pre class="brush: java; title: ; notranslate">	XMLNode sectionNode= (XMLNode)document.selectSingleNode(&quot;/catalog/
	journal:journal/journal:article/@journal:section&quot;, resolver);
	section=sectionNode.getNodeValue();
</pre>
<p>As a contrast b etween the selectSingleNode method that takes an NSResolver and the selectSingleNode method that doesn&#8217;t, the method that doesn&#8217;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:</p>
<pre class="brush: java; title: ; notranslate">	XSLException Namespace prefix 'journal' used but not declared.
</pre>
<h2>Method selectNodes(String,NSResolver)</h2>
<p>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:</p>
<pre class="brush: java; title: ; notranslate">	NodeList nodeList=document.selectNodes(&quot;/catalog/journal:journal[@
	journal:date='November-December 2008']/journal:article/title&quot;,
	resolver );
</pre>
<p>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.</p>
<pre class="brush: java; title: ; notranslate">	for(int i=0; i&lt;nodeList.getLength(); i++){
	   titleNode=(XMLElement)nodeList.item(i);
	   title=titleNode.getFirstChild().getNodeValue();
	   System.out.println(title);
	}
</pre>
<h2>Running the Java application</h2>
<p>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:</p>
<ol>
<li>First, we import the required packages from XDK 11g.
<pre class="brush: java; title: ; notranslate">	import oracle.xml.parser.v2.*;
	import java.io.*;
	import org.xml.sax.SAXException;
	import org.w3c.dom.*;
</pre>
</li>
<li>Next, we add the XPathParser Java class declaration.
<pre class="brush: java; title: ; notranslate">	public class XPathParser{
</pre>
</li>
<li>We define the parseDocument method to parse an XML document with the DOMParser.</li>
</ol>
<pre class="brush: java; title: ; notranslate">	public void parseDocument(File xmlDocument){
	   try{
</pre>
<ul>
<li>Next, we create a DOMParser object and parse the XML document.
<pre class="brush: java; title: ; notranslate">	DOMParser domParser=new DOMParser();
	domParser.parse(new FileReader(xmlDocument));
	XMLDocument document=domParser.getDocument();
</pre>
</li>
<li>We specify the NSResolver object to resolve namespaces.
<pre class="brush: java; title: ; notranslate">	CustomResolver resolver=new CustomResolver();
	resolver.resolveNamespacePrefix(&quot;journal&quot;);
</pre>
</li>
<li>Next, we select nodes using the selectSingleNode(String) method.
<pre class="brush: java; title: ; notranslate">	XMLNodetitleNode=(XMLNode)document.selectSingleNode
	(&quot;/catalog/journal/article[@section=' ORACLE DEVELOPER']/title&quot;);
	String title=titleNode.getFirstChild().getNodeValue();
	System.out.println(&quot;Title of first Article in ORACLE DEVELOPER
	Section (with nodes not in any namespace) is &quot;+ title);
	XMLNode authorNode=(XMLNode)document.selectSingleNode(&quot;/catalog/
	journal/article[title= Oracle Database 11g Redux']/author&quot;);
	String author=authorNode.getFirstChild().getNodeValue();
	   System.out.println(&quot;Author of Title Oracle Database 11g Redux
	   is &quot;+ author);
	   XMLNode sectionNode=(XMLNode)document.selectSingleNode
	   (&quot;/catalog/journal[@date=March-April 2008']/article[2]
	   /@section&quot;);
	String section=sectionNode.getNodeValue();
	System.out. println(&quot;Section of 2nd Article in Journal of date
	March-April 2008 is &quot;+ section);
</pre>
</li>
<li>We select nodes using the selectNodes(String) method.
<pre class="brush: java; title: ; notranslate">	NodeList nodeList = document.selectNodes(&quot;/catalog/journal[@date=
	'March-April 2008']/article/title&quot;);
	System.out.println(&quot;Article Titles published in journal of March-
	April 2008 are: &quot;);
	for(int i=0; i&lt;nodeList.getLength(); i++){
	   titleNode=(XMLElement)nodeList.item(i);
	   title=titleNode.getFirstChild().getNodeValue();
	   System.out.println(title);
	}
	nodeList=document.selectNodes(&quot;/catalog/journal[@date='March-April
	2008']/article/@section&quot;);
	System.out.println(&quot;Articles in journal of March-April 2008 were
	published in Sections: &quot;);
	for(int i=0; i&lt;nodeList.getLength(); i++){
	   sectionNode=(XMLNode)nodeList.item(i);
	   section=sectionNode.getNodeValue();
	   System.out.println(section+&quot; &quot;);
	}
</pre>
</li>
<li>Next, we select nodes using the selectSingleNode(String,NSResolver) method.
<pre class="brush: java; title: ; notranslate">
	sectionNode=(XMLNode)document.selectSingleNode(&quot;/catalog/journal:
	journal/journal:article/@journal:section&quot;, resolver);
	section=sectionNode.getNodeValue();
	System.out.println(&quot;Section of first article in first journal
	(nodes being in journal namespace) is &quot;+section+&quot; &quot;);
	System.out.println(&quot;Titles for articles in journal of date
	November-December 2008 (journal, article, and date nodes being in
	journal namespace) are &quot;);
</pre>
</li>
<li>We also select nodes using the selectNodes(String,NSResolver) method.
<pre class="brush: java; title: ; notranslate">	nodeList=document.selectNodes(&quot;/catalog/journal:journal[@journal:
	date= 'November-December 2008']/journal:article/title&quot;,
	resolver );
	for(int i=0; i&lt;nodeList.getLength(); i++){
	   titleNode=(XMLElement)nodeList.item(i);
	   title=titleNode.getFirstChild().getNodeValue();
	   System.out.println(title);
	   }
	   }catch(IOException e){
	      System.err.println(&quot;IOException&quot;+e.getMessage());
	   }
	   catch(XMLDOMException e){
	      System.err.println(&quot;XMLDOMException&quot;+e.getMessage());
	   }
	   catch(XMLParseException e)
	      {System.err.println(&quot;XMLParseException&quot;+e.getMessage());
	   }
	   catch(XSLException e){
	      System.err.println(&quot;XSLException&quot;+e.getMessage());
	   }
	   catch(SAXException e){
	      System.err.println(&quot;SAXException&quot;+e.getMessage());
	   }
	}
</pre>
</li>
<li>We add the Java class that extends the NSResolver class.
<pre class="brush: java; title: ; notranslate">	class CustomResolver implements NSResolver{
	public java.lang.String
	resolveNamespacePrefix(java.lang.String prefix){
	if(prefix.equals(&quot;journal&quot;)){
	   return new &quot;http://www.xdk11g.com/xpath&quot;;
	}else
	   return null;
	   }
	}
</pre>
</li>
<li>Finally, we define the main method in which we create an instance of the
<pre class="brush: java; title: ; notranslate">	XPathParser class and invoke the parseDocument method.
	   public static void main(String[] argv){
	      XPathParser parser=new XPathParser();
	      parser.parseDocument(new File(&quot;catalog.xml&quot;));
	   }
	}
</pre>
</li>
</ul>
<p>To run the XPathParser.java application in JDeveloper, right-click on the <b>XPathParser.java</b> node in the <b>Application Navigator</b>, and select <b>Run</b>. The output from the XPathParser.java application is shown in the following illustration:</p>
<h2>Summary</h2>
<p>In this chapter you learned about XPath support in JDeveloper 11g. JDeveloper provides an <b>XPath Search</b> 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&#8217;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 <b>XSLT(Extensible Stylesheet Language Transformation)</b> support in JDeveloper.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2009/04/what-is-xpath/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>XML Schema Elements &#8211; Part2</title>
		<link>http://www.javabeat.net/2009/03/xml-schema-elements-part2/</link>
		<comments>http://www.javabeat.net/2009/03/xml-schema-elements-part2/#comments</comments>
		<pubDate>Wed, 25 Mar 2009 04:44:06 +0000</pubDate>
		<dc:creator>JavaBeat</dc:creator>
				<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=505</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Complex Elements Complex elements are those which contain other elements as children or these elements have attributes. Empty elements and elements containing only text are also considered complex. The following is an examples of complex element 1 2 3 4 5 6 &#60;employee grade=&#34;senior&#34;&#62; &#60;id&#62;745821&#60;/id&#62; &#60;empName&#62;Tim&#60;/empName&#62; &#60;salary&#62;35000&#60;/salary&#62; &#60;domain&#62;Insurance&#60;/domain&#62; &#60;/employee&#62; Define Complex Type in XML schema [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h3>Complex Elements</h3>
<p>Complex elements are those which contain other elements as children or these elements have attributes. Empty elements and elements containing only text are also considered complex. The following is an examples of complex element</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;employee grade=&quot;senior&quot;&gt;
	&lt;id&gt;745821&lt;/id&gt;
	&lt;empName&gt;Tim&lt;/empName&gt;
	&lt;salary&gt;35000&lt;/salary&gt;
	&lt;domain&gt;Insurance&lt;/domain&gt;
&lt;/employee&gt;</pre></td></tr></table></div>

<h4>Define Complex Type in XML schema</h4>
<p>Complex types can be defined in XML schema as demonstrated in this example:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;employee&quot;&gt;
    &lt;xs:complexType&gt;
      &lt;xs:sequence&gt;
	&lt;xs:element name=&quot;id&quot; type=&quot;xs:string&quot;/&gt;
	&lt;xs:element name=&quot;empName&quot; type=&quot;xs:string&quot;/&gt;
	&lt;xs:element name=&quot;salary&quot; type=&quot;xs:string&quot;/&gt;
	&lt;xs:element name=&quot;domain&quot; type=&quot;xs:string&quot;/&gt;
      &lt;/xs:sequence&gt;
    &lt;/xs:complexType&gt;
&lt;/xs:element&gt;</pre></td></tr></table></div>

<h3>Define empty elements</h3>
<p>Consider the following XML element:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;employee empId=&quot;157117&quot; /&gt;</pre></td></tr></table></div>

<p>This empty element can be defined in XML schema as follows:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;employee&quot;&gt;
  &lt;xs:complexType&gt;
    &lt;xs:attribute name=&quot;empId&quot; type=&quot;xs:positiveInteger&quot;/&gt;
  &lt;/xs:complexType&gt;
&lt;/xs:element&gt;</pre></td></tr></table></div>

<p>Here we can see that in the definition we dont define any child elements. We just define the attribute.</p>
<h4>Define text only elements</h4>
<p>Consider the following XML element:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;domain&gt;BFS&lt;/domain&gt;</pre></td></tr></table></div>

<p>The above element can be defined in XML schema as follows:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;domain&quot;&gt;
  &lt;xs:complexType&gt;
    &lt;xs:simpleContent&gt;
      &lt;xs:extension base=&quot;xs:string&quot; /&gt;
    &lt;/xs:simpleContent&gt;
  &lt;/xs:complexType&gt;
&lt;/xs:element&gt;</pre></td></tr></table></div>

<p>Here, we define that the content of the complex type is simple. In schema terms simple means plain text. The <b>xs:extension</b> is used to declare the type of the data.</p>
<h3>Define Mixed Content</h3>
<p>Sometimes an XML element can contain elements and text combined. Consider the following example:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;employeeInfo&gt;
The employee &lt;id&gt;134567&lt;/id&gt;
belongs to &lt;domain&gt;BFS&lt;/domain&gt;
and his salary is &lt;salary&gt;56430&lt;/salary&gt;
&lt;/employeeInfo&gt;</pre></td></tr></table></div>

<p>The above fragment can be defined in XML schema as follows:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;employeeInfo&quot;&gt;
  &lt;xs:complexType mixed=&quot;true&quot;&gt;
    &lt;xs:sequence&gt;
      &lt;xs:element name=&quot;id&quot; type=&quot;xs:positiveInteger&quot;/&gt;
      &lt;xs:element name=&quot;domain&quot; type=&quot;xs:string&quot;/&gt;
      &lt;xs:element name=&quot;salary&quot; type=&quot;xs:positiveInteger&quot;/&gt;
    &lt;/xs:sequence&gt;
  &lt;/xs:complexType&gt;
&lt;/xs:element&gt;</pre></td></tr></table></div>

<p>In the defined XML schema we use the attribute <b>mixed</b> and set its value as true. This indicates that the XML element can contain other elements and simple text as it children</p>
<h2>XSD Indicators</h2>
<p>Using XSD Indicator a desicion can be made about how to use Complex types elements in a XML document. The indicators are basically divided into three groups :</p>
<ul>
<li>Order indicators</li>
<li>Occurrence indicators</li>
<li>Group indicators</li>
</ul>
<p>Let us know look at each of these categories.</p>
<h3>Order Indicators</h3>
<p>The order indicators define the ordering of the elements or the sequence in which the elements appear in the XML document. This group of indicators has three types of indicators :</p>
<ul>
<li>All</li>
<li>Choice</li>
<li>Sequence</li>
</ul>
<p><u>All</u></p>
<p>Using the <b>All</b> indicator allows the child elements to appear in any order. However, it sets a restriction that each child must appear only once. Lets look at an example :</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;employee&quot;&gt;
  &lt;xs:complexType&gt;
    &lt;xs:all&gt;
      &lt;xs:element name=&quot;empId&quot; type=&quot;xs:string&quot;/&gt;
      &lt;xs:element name=&quot;name&quot; type=&quot;xs:string&quot;/&gt;
      &lt;xs:element name=&quot;salary&quot; type=&quot;xs:integer&quot;/&gt;
      &lt;xs:element name=&quot;domain&quot; type=&quot;xs:string&quot;/&gt;
    &lt;/xs:all&gt;
  &lt;/xs:complexType&gt;
&lt;/xs:element&gt;</pre></td></tr></table></div>

<p><u>Choice</u></p>
<p>The <b>Choice</b> indicators specifies that out of all the child elements one can appear. Lets look at an example:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;employee&quot;&gt;
  &lt;xs:complexType&gt;
    &lt;xs:choice&gt;
      &lt;xs:element name=&quot;manager&quot; type=&quot;manager&quot;/&gt;
      &lt;xs:element name=&quot;member&quot; type=&quot;member&quot;/&gt;
    &lt;/xs:choice&gt;
  &lt;/xs:complexType&gt;
&lt;/xs:element&gt;</pre></td></tr></table></div>

<p><u>Sequence</u></p>
<p>This indicator specfies that the child elements should follow the specified order :</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;employee&quot;&gt;
  &lt;xs:complexType&gt;
    &lt;xs:sequence&gt;
      &lt;xs:element name=&quot;empId&quot; type=&quot;xs:string&quot;/&gt;
      &lt;xs:element name=&quot;name&quot; type=&quot;xs:string&quot;/&gt;
      &lt;xs:element name=&quot;salary&quot; type=&quot;xs:integer&quot;/&gt;
      &lt;xs:element name=&quot;domain&quot; type=&quot;xs:string&quot;/&gt;
    &lt;/xs:sequence&gt;
  &lt;/xs:complexType&gt;
&lt;/xs:element&gt;</pre></td></tr></table></div>

<h3>Occurrence Indicators</h3>
<p>The occurrence indiactor defines the number of times an element can appear. This group has two differetn types:</p>
<ul>
<li>maxOccurs</li>
<li>minOccurs</li>
</ul>
<p><u>maxOccurs</u></p>
<p>The <b>maxOccurs</b> element sets an upper limit on the number of times an element can upper. Lets looks at an example:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;employee&quot;&gt;
  &lt;xs:complexType&gt;
    &lt;xs:sequence&gt;
      &lt;xs:element name=&quot;empId&quot; type=&quot;xs:string&quot;/&gt;
      &lt;xs:element name=&quot;name&quot; type=&quot;xs:string&quot;/&gt;
      &lt;xs:element name=&quot;salary&quot; type=&quot;xs:integer&quot;/&gt;
      &lt;xs:element name=&quot;domain&quot; type=&quot;xs:string&quot;/&gt;
      &lt;xs:element name=&quot;project&quot; type=&quot;xs:string&quot; maxOccurs=&quot;10&quot;/&gt;
    &lt;/xs:sequence&gt;
  &lt;/xs:complexType&gt;
&lt;/xs:element&gt;</pre></td></tr></table></div>

<p><u>minOccurs</u></p>
<p>The <b>minOccurs</b> element sets the lower imit on the number of times an element can upper. Lets looks at an example:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;employee&quot;&gt;
  &lt;xs:complexType&gt;
    &lt;xs:sequence&gt;
      &lt;xs:element name=&quot;empId&quot; type=&quot;xs:string&quot;/&gt;
      &lt;xs:element name=&quot;name&quot; type=&quot;xs:string&quot;/&gt;
      &lt;xs:element name=&quot;salary&quot; type=&quot;xs:integer&quot;/&gt;
      &lt;xs:element name=&quot;domain&quot; type=&quot;xs:string&quot;/&gt;
      &lt;xs:element name=&quot;project&quot; type=&quot;xs:string&quot; maxOccurs=&quot;10&quot; minOccurs=&quot;0&quot;/&gt;
    &lt;/xs:sequence&gt;
  &lt;/xs:complexType&gt;
&lt;/xs:element&gt;</pre></td></tr></table></div>

<h3>Group Indicators</h3>
<p>Group indicators allow us to define a group of elements</p>
<ul>
<li>Group name</li>
<li>attributeGroup name</li>
</ul>
<p><u>Group Name</u></p>
<p>The group indicator is used to define a group of elements. Once defined the group can be referenced in other places within the XML schema. Lets look at an example :</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:group name=&quot;projectGroup&quot;&gt;
  &lt;xs:sequence&gt;
    &lt;xs:element name=&quot;projectname&quot; type=&quot;xs:string&quot;/&gt;
    &lt;xs:element name=&quot;technology&quot; type=&quot;xs:string&quot;/&gt;
  &lt;/xs:sequence&gt;
&lt;/xs:group&gt;</pre></td></tr></table></div>

<p>In the above example we define a group named <b>projectGroup</b>. Now we will see how to refer this group in other places :</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;employee&quot;&gt;
  &lt;xs:complexType&gt;
    &lt;xs:sequence&gt;
      &lt;xs:element name=&quot;empId&quot; type=&quot;xs:string&quot;/&gt;
      &lt;xs:element name=&quot;name&quot; type=&quot;xs:string&quot;/&gt;
      &lt;xs:element name=&quot;salary&quot; type=&quot;xs:integer&quot;/&gt;
      &lt;xs:element name=&quot;domain&quot; type=&quot;xs:string&quot;/&gt;
      &lt;xs:group ref=&quot;projectGroup&quot;/&gt;
    &lt;/xs:sequence&gt;
  &lt;/xs:complexType&gt;
&lt;/xs:element&gt;</pre></td></tr></table></div>

<p>After making a reference to the <b>projectGroup</b> the employee element gets a total of six child elements:<br />
<b>empId, name, salary, domain, projectname, technology</b></p>
<p>.</p>
<p><u>Attribute Groups</u></p>
<p>The attribute group is used to group together a set of attributes. Once defined the group can be referenced in other elements to define the attributes for a element. Lets look at an example :</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:attributeGroup name=&quot;empAttrGroup&quot;&gt;
    &lt;xs:attribute name=&quot;designation&quot; type=&quot;xs:string&quot;/&gt;
&lt;/xs:attributeGroup&gt;
&nbsp;
&lt;xs:complexType name=&quot;employee&quot;&gt;
    &lt;xs:attributeGroup ref=&quot;empAttrGroup&quot;/&gt;
&lt;/xs:complexType&gt;</pre></td></tr></table></div>

<p><u>The <any> Element</u></p>
<p>With the use of the <b>any</b> element an XML schema can can extend another XML schema. Lets look at an example :</p>
<p><b>Filename : employee.xsd</b></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;employee&quot;&gt;
  &lt;xs:complexType&gt;
    &lt;xs:sequence&gt;
      &lt;xs:element name=&quot;empId&quot; type=&quot;xs:positiveinteger&quot;/&gt;
      &lt;xs:element name=&quot;name&quot; type=&quot;xs:string&quot;/&gt;
      &lt;xs:element name=&quot;salary&quot; type=&quot;xs:positiveinteger&quot;/&gt;
      &lt;xs:element name=&quot;domain&quot; type=&quot;xs:string&quot;/&gt;
      &lt;xs:any minOccurs=&quot;0&quot;/&gt;
    &lt;/xs:sequence&gt;
  &lt;/xs:complexType&gt;
&lt;/xs:element&gt;</pre></td></tr></table></div>

<p>Filename : children.xsd</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;project&quot;&gt;
  &lt;xs:complexType&gt;
    &lt;xs:sequence&gt;
      &lt;xs:element name=&quot;projectName&quot; type=&quot;xs:string&quot; /&gt;
      &lt;xs:element name=&quot;technologyUsed&quot; type=&quot;xs:string&quot; /&gt;
    &lt;/xs:sequence&gt;
  &lt;/xs:complexType&gt;
&lt;/xs:element&gt;</pre></td></tr></table></div>

<p>The XML file can use components from both the files:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;employee&gt;
	&lt;empId&gt;143233&lt;/empId&gt;
	&lt;name&gt;John&lt;/name&gt;
	&lt;salary&gt;34500&lt;/salary&gt;
	&lt;domain&gt;Insurance&lt;/domain&gt;
	&lt;project&gt;
		&lt;projectName&gt;ISD&lt;/projectName&gt;
		&lt;technologyUsed&gt;.NET&lt;/technologyUsed&gt;
	&lt;/project&gt;
&lt;/employee&gt;</pre></td></tr></table></div>

<h2>XSD Data Types</h2>
<p><b>String</b></p>
<p>The string data type is used to store characters and strings. For e.g:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">	&lt;table border=&quot;1&quot;&gt;
	&lt;tr&gt;
		&lt;td&gt;XML Schema&lt;/td&gt;
		&lt;td&gt;&lt;xs:element name=&quot;name&quot; type=&quot;xs:string&quot;/&gt;&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td&gt;XML&lt;/td&gt;
		&lt;td&gt;&lt;name&gt;John&lt;/name&gt;&lt;/td&gt;
	&lt;/tr&gt;
	&lt;/table&gt;</pre></td></tr></table></div>

<p><b>Date</b></p>
<p>The date type represents a date. The date represented by using the date datatype is specified in the following format : <b>YYYY-MM-DD</b>.<br />
For e.g:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;table border=&quot;1&quot;&gt;
&lt;tr&gt;
	&lt;td&gt;XML Schema&lt;/td&gt;
	&lt;td&gt;&lt;xs:element name=&quot;joiningDate&quot; type=&quot;xs:date&quot;/&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
	&lt;td&gt;XML&lt;/td&gt;
	&lt;td&gt;&lt;joiningDate&gt;2007-03-27&lt;/joiningDate&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;</pre></td></tr></table></div>

<p><b>Numeric</b></p>
<p>The numeric data types are of two types:</p>
<ul>
<li>Decimal</li>
<p>The decimal data type is used to represent decimal numbers. For e.g:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;table border=&quot;1&quot;&gt;
&lt;tr&gt;
	&lt;td&gt;XML Schema&lt;/td&gt;
	&lt;td&gt;&lt;xs:element name=&quot;price&quot; type=&quot;xs:decimal&quot;/&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
	&lt;td&gt;XML&lt;/td&gt;
	&lt;td&gt;&lt;price&gt;678.50&lt;/price&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;</pre></td></tr></table></div>

<li>Integer</li>
<p>The integer data type is used to represent integers. For e.g:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;table border=&quot;1&quot;&gt;
&lt;tr&gt;
	&lt;td&gt;XML Schema&lt;/td&gt;
	&lt;td&gt;&lt;xs:element name=&quot;salary&quot; type=&quot;xs:integer&quot;/&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
	&lt;td&gt;XML&lt;/td&gt;
	&lt;td&gt;&lt;salary&gt;678.50&lt;/salary&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;</pre></td></tr></table></div>

</ul>
<p><b>Other Datatypes</b></p>
<ul>
<li>Boolean</li>
<p>The boolean datatype represents the value true or false.E.g:</p>
<table border="1">
<tr>
<td>XML Schema</td>
<td><xs:attribute name="terminated" type="xs:boolean"/></td>
</tr>
<tr>
<td>XML</td>
<td><employee terminated="false">John</employee></td>
</tr>
</table>
</ul>
<p>[Note: If one wants to test these examples then you should have a suitable XML editor. By simply copying the files in your system and executing them in the browser wont produce the expected output.]</p>
<h3>XML Reference</h3>
<ul>
<li><a href="http://www.javabeat.net/tips/186-xml-schema-elements.html">XML Schema Elements</a></li>
<li><a href="http://www.javabeat.net/tips/185-xforms.html">XForms</a></li>
<li><a href="http://www.javabeat.net/tips/184-creating-xslt-documents.html">Creating XSLT documents</a></li>
<li><a href="http://www.javabeat.net/tips/183-how-to-use-xlink-and-xpointer.html">How to use XLink and XPointer?</a></li>
<li><a href="http://www.javabeat.net/tips/182-how-to-query-xml-using-xpath.html">How to Query XML using XPath</a></li>
</ul>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2009/03/xml-schema-elements-part2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>XML Schema Elements</title>
		<link>http://www.javabeat.net/2009/03/xml-schema-elements/</link>
		<comments>http://www.javabeat.net/2009/03/xml-schema-elements/#comments</comments>
		<pubDate>Sat, 21 Mar 2009 04:43:29 +0000</pubDate>
		<dc:creator>JavaBeat</dc:creator>
				<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=503</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>XML schema is a language for describing the contents and structure of a XML document. It basically creates a blue print of the actual XML document by describing everything about the elements which can appear in the document. By creating a XML schema we make the XML document conform to the rules defined in the [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>
XML schema is a language for describing the contents and structure of a XML document. It basically creates a blue print of the actual XML document by describing everything about the elements which can appear in the document. By creating a XML schema we make the XML document conform to the rules defined in the XML schema. It essentially says that the XML document cant break the rules defined in the XML schema document.
</p>
<p>
Lets create a sample XML schema document <i>empSchema.xsd</i>:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot; ?&gt;
&lt;xs:schema xmlns:xs=&quot;http://www.w3.org/2001/XMLSchema&quot;&gt;
&lt;xs:element name=&quot;employee&quot;&gt;
    &lt;xs:complexType&gt;
      &lt;xs:sequence&gt;
	&lt;xs:element name=&quot;id&quot; type=&quot;xs:string&quot;/&gt;
	&lt;xs:element name=&quot;empName&quot; type=&quot;xs:string&quot;/&gt;
	&lt;xs:element name=&quot;salary&quot; type=&quot;xs:string&quot;/&gt;
	&lt;xs:element name=&quot;domain&quot; type=&quot;xs:string&quot;/&gt;
      &lt;/xs:sequence&gt;
    &lt;/xs:complexType&gt;
&lt;/xs:element&gt;
&lt;/xs:schema&gt;</pre></td></tr></table></div>

<p>Lets create a XML document <i>employee.xml</i>:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;?xml version=&quot;1.0&quot;?&gt;
&lt;employee
xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xsi:noNamespaceSchemaLocation=&quot;empSchema.xsd&quot;&gt;
	&lt;id&gt;745821&lt;/id&gt;
	&lt;empName&gt;Tim&lt;/empName&gt;
	&lt;salary&gt;35000&lt;/salary&gt;
	&lt;domain&gt;Insurance&lt;/domain&gt;
&lt;/employee&gt;</pre></td></tr></table></div>

<p>In the XML document above we see that the document is referring to a XSD document[xsi:noNamespaceSchemaLocation="empSchema.xsd"]. XSD is nothing but a file which defines XML schema.<br />
I will explain the details of the XML schema document as we go along. The above example is just supposed to give you a feel of what an XML schema looks like and how to refer to the XSD from a XML file.
</p>
<p><h2>XML Schema Elements</h2>
<h3>schema</h3>
<p>Every XML schema starts with <b><schema></b> element as the root. The attribute <b>xmlns:xs=&#8221;http://www.w3.org/2001/XMLSchema&#8221;</b> says that the elements in the XML document belong to the <b>&#8220;http://www.w3.org/2001/XMLSchema&#8221;</b> namespace  and each of the elements that belong to this namespace should be prefixed with the <b>xs</b>.
</p>
<p><h2>Simple Type</h2>
<p>A simple type element cannot contain any other elements or attributes. It can contain only text data.  For E.g:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;table&gt;
&lt;tr&gt;
&lt;td&gt;Syntax:&lt;/td&gt;
&lt;td&gt;&lt;xs:element name=&quot;element-name&quot; type=&quot;data-type&quot;/&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;XML Schema:&lt;/td&gt;
&lt;td&gt;&lt;xs:element name=&quot;empName&quot; type=&quot;xs:string&quot;/&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;XML:&lt;/td&gt;
&lt;td&gt;&lt;empName&gt;Daniel&lt;/empName&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;</pre></td></tr></table></div>

<p>The allowed datatypes in XML schema are :</p>
<table border="1" style="background-color:#EFEFEF">
<tr>
<td>xs:string</td>
</tr>
<tr>
<td>xs:decimal</td>
</tr>
<tr>
<td>xs:integer</td>
</tr>
<tr>
<td>xs:boolean</td>
</tr>
<tr>
<td>xs:date</td>
</tr>
<tr>
<td>xs:time</td>
</tr>
</table>
<h3>Attributes</h3>
<p>An attribute provides additional information about the element. Simple types cannot have attributes. However the attribute itself are of type simple. Let us now look at the syntax and an example of how to define attributes in XML Schema:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;table&gt;
&lt;tr&gt;
&lt;td&gt;Syntax:&lt;/td&gt;
&lt;td&gt;&lt;xs:attribute name=&quot;attribute-name&quot; type=&quot;data-type&quot;/&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;XML Schema:&lt;/td&gt;
&lt;td&gt;&lt;xs:attribute name=&quot;grade&quot; type=&quot;xs:string&quot;/&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;XML:&lt;/td&gt;
&lt;td&gt;&lt;employee grade=&quot;senior&quot;&gt;Daniel&lt;/employee&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;</pre></td></tr></table></div>

</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<h3>Content Restrictions</h3>
<p>
When an element or an attribute is defined with a particular data type, it essentially means that the element or attribute cant be assigned a value which is of some other type. In XML schema we can define custom restrictions on elements. Such restrictions are called <b>facets</b>. </p>
<ul>
<li><b>Value restrictions</b></li>
<p>
Using value restrictions the XML schema places a restriction that the value of the element should be between a allowed range.In the following example element a restriction is placed on the salary element that its value cannot be less that zero and more than 85000.<br />
In case it happens then the XML document will not validate:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;salary&quot;&gt;
	&lt;xs:simpleType&gt;
		&lt;xs:restriction base=&quot;xs:integer&quot;&gt;
			&lt;xs:minInclusive value=&quot;0&quot;/&gt;
			&lt;xs:maxInclusive value=&quot;85000&quot;/&gt;
		&lt;/xs:restriction&gt;
	&lt;/xs:simpleType&gt;
&lt;/xs:element&gt;</pre></td></tr></table></div>

<li><b>Restriction on a set</b></li>
<p>
In set restriction the value of an element should be set from only an allowed set of values. In the following example the value of the domain element is limited to a certain set of values:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;domain&quot;&gt;
	&lt;xs:simpleType&gt;
		&lt;xs:restriction base=&quot;xs:string&quot;&gt;
			&lt;xs:enumeration value=&quot;BFS&quot;/&gt;
			&lt;xs:enumeration value=&quot;Insurance&quot;/&gt;
			&lt;xs:enumeration value=&quot;Manlog&quot;/&gt;
			&lt;xs:enumeration value=&quot;Life Sciences&quot;/&gt;
		 &lt;/xs:restriction&gt;
	&lt;/xs:simpleType&gt;
&lt;/xs:element&gt;</pre></td></tr></table></div>

<li><b>Restriction on a series</b></li>
<p>In such type of restriction we can use any valid regular expression syntax to define the restrictions. In the following example we define a restriction that the number should be between 0 and 9.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;number&quot;&gt;
	&lt;xs:simpleType&gt;
		&lt;xs:restriction base=&quot;xs:string&quot;&gt;
			&lt;xs:pattern value=&quot;[0-9]&quot;/&gt;
		&lt;/xs:restriction&gt;
	&lt;/xs:simpleType&gt;
&lt;/xs:element&gt;</pre></td></tr></table></div>

<li><b>Restriction on a whitespace characters</b></li>
<p>These restrictions define how the whitespace characters are handled in the XML document. The restriction can be placed using the following syntax:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:whiteSpace value=&quot;preserve&quot;/&gt;
or
&lt;xs:whiteSpace value=&quot;replace&quot;/&gt;</pre></td></tr></table></div>

<p>The attribute value <b>preserve</b> says that the whitespace characters will not be removed by the XML processor. The attribute value <b>replace</b> says that the following characters will be replaced by spaces :<br />
line feeds, tabs, spaces, and carriage returns. Lets looks at an example now :</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;feedback&quot;/&gt;
	&lt;xs:simpleType&gt;
		&lt;xs:restriction base=&quot;xs:string&quot;/&gt;
			&lt;xs:whiteSpace value=&quot;preserve&quot;/&gt;
		&lt;/xs:restriction/&gt;
	&lt;/xs:simpleType/&gt;
&lt;/xs:element/&gt;</pre></td></tr></table></div>

<li><b>Restriction on the length</b></li>
<p>
This places a restriction on the allowed numbers of characters. The following example places a restriction that the employee id cannot be more than 6 characters</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xs:element name=&quot;empId&quot;&gt;
&lt;xs:simpleType&gt;
	&lt;xs:restriction base=&quot;xs:integer&quot;&gt;
		&lt;xs:length value=&quot;6&quot;/&gt;
	&lt;/xs:restriction&gt;
&lt;/xs:simpleType&gt;
&lt;/xs:element&gt;</pre></td></tr></table></div>

</ul>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2009/03/xml-schema-elements/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating XSLT documents</title>
		<link>http://www.javabeat.net/2009/03/creating-xslt-documents/</link>
		<comments>http://www.javabeat.net/2009/03/creating-xslt-documents/#comments</comments>
		<pubDate>Thu, 12 Mar 2009 04:42:14 +0000</pubDate>
		<dc:creator>JavaBeat</dc:creator>
				<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=499</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Introduction XSLT is used for the transformation of XML documents into XHTML. We know that HTML uses predefined set of tags which can be interpreted by the browser. However this is not true for XML documents. XML does not use predefined set of tags. Hence, if we open an XML document in browser we cant [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>Introduction</h2>
<p>
<b>XSLT</b> is used for the transformation of XML documents into XHTML. We know that HTML uses predefined set of tags which can be interpreted by the browser. However this is not true for XML documents. XML does not use predefined set of tags. Hence, if we open an XML document in browser we cant expect the browser to display the document in some meaningful format.</p>
<p>This is where XSLT comes into picture. Using <b>XSLT</b> we can define rules for each XML element in the XML document. Those rules decide how to display the corresponding XML element. <b>XSLT</b> does a transformation of each XML element into a HTML element. With XSLT we can not only display the XML elements in a meaningful way but also filters the elements, sort the elements. <b>XSLT</b> can  be compared with Cascading Style Sheets (CSS). CSS defines the formating rules for HTML tags, <b>XSLT</b> defines the formatting rules for XML tags.
</p>
<p>
We will be using the following XML document to understand the basic of <b>XSLT</b> : <br />
File Name : <b>employees.xml</b></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;
&lt;employees&gt;
	&lt;employee vertical=&quot;banking&quot;&gt;
		&lt;id&gt;17452&lt;/id&gt;
		&lt;name&gt;Jason&lt;/name&gt;
		&lt;experience&gt;2&lt;/experience&gt;
		&lt;salary&gt;35000&lt;/salary&gt;
	&lt;/employee&gt;
&nbsp;
	&lt;employee vertical=&quot;insurance&quot;&gt;
		&lt;id&gt;14782&lt;/id&gt;
		&lt;name&gt;Jim&lt;/name&gt;
		&lt;experience&gt;3&lt;/experience&gt;
		&lt;salary&gt;45000&lt;/salary&gt;
	&lt;/employee&gt;
&nbsp;
	&lt;employee vertical=&quot;telecom&quot;&gt;
		&lt;id&gt;12563&lt;/id&gt;
		&lt;name&gt;Charles&lt;/name&gt;
		&lt;experience&gt;4&lt;/experience&gt;
		&lt;salary&gt;55000&lt;/salary&gt;
	&lt;/employee&gt;
&lt;/employees&gt;</pre></td></tr></table></div>

</p>
<h2>Link the XSL Style Sheet to the XML Document</h2>
<p>To apply <b>XSLT</b> formatting to the XML document we need to tell the XML document about the <b>XSLT</b>. We can do this by adding the following line to the XML document : <br />
<b><?xml-stylesheet type="text/xsl" href="employees.xsl"?></b>
</p>
<h2>Creating XSLT documents</h2>
<h3>The root element</h2>
<p>
As with XML every <b>XSLT</b> document must also start with a root element. The root element should be <b><xsl:stylesheet> or <xsl:transform></b>. <br />For E.g :</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;xsl:stylesheet version=&quot;1.0&quot; xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot;&gt;
or
&lt;xsl:transform version=&quot;1.0&quot; xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot;&gt;</pre></td></tr></table></div>

<p>By adding the XSLT namespace attribute, <b>xmlns:xsl</b>, access is provided to elements, attributes.<br />
The value of <b>xmlns:xsl</b> points to the official W3C <b>XSLT</b> namespace. We must also include the atribute <b>version</b>.
</p>
<h3>Defining templates</h3>
<p>
In <b>XSLT</b> we can define templates. Templates define a set of rules for nodes. These rules produce a desired display for a node on which the template is applied. In <b>XSLT</b> templates can be defined using <b>xsl:template</b> element.
</p>
<p><b>xsl:template</b> element has a <b>match</b> attribute which associates a template with an XML element.<br />
With the match element we can also associate a template with the entire document.</p>
<p>For E.g :</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;
&nbsp;
&lt;xsl:stylesheet version=&quot;1.0&quot; xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot;&gt;
&lt;xsl:template match=&quot;/&quot;&gt;
 &lt;html&gt;
 &lt;body&gt;
   &lt;table border=&quot;1&quot;&gt;
     &lt;tr bgcolor=&quot;#9acd32&quot;&gt;
       &lt;th&gt;Id&lt;/th&gt;
       &lt;th&gt;Name&lt;/th&gt;
     &lt;/tr&gt;
   &lt;/table&gt;
 &lt;/body&gt;
 &lt;/html&gt;
&lt;/xsl:template&gt;
&lt;/xsl:stylesheet&gt;</pre></td></tr></table></div>

<p><b>Output</b>:</p>
<table border="1">
<tr bgcolor="#9acd32">
<th>Id</th>
<th>Name</th>
</tr>
</table>
<p>
<b>Explanation</b>:<br />
This is just a trivial example where we dont do much expect creating two headers. In the example above the <b>xsl:template</b> element associates the template to the root element. This is achieved by using <b>match=&#8221;/&#8221;</b>. This essesntially says if the xml root element is encountered then apply this template. Inside the template we define some HTML to display.
</p>
<p><h3>Extracting values of XML elements</h3>
<p>We can extract the values of XML elements using the <b>xsl:value-of</b> element. <br />
For E.g:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;
&lt;xsl:stylesheet version=&quot;1.0&quot; xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot;&gt;
&lt;xsl:template match=&quot;/&quot;&gt;
 &lt;html&gt;
 &lt;body&gt;
   &lt;table border=&quot;1&quot;&gt;
     &lt;tr bgcolor=&quot;#9acd32&quot;&gt;
       &lt;th&gt;Id&lt;/th&gt;
       &lt;th&gt;Name&lt;/th&gt;
     &lt;/tr&gt;
     &lt;tr&gt;
      &lt;td&gt;&lt;xsl:value-of select=&quot;employees/employee/id&quot;/&gt;&lt;/td&gt;
      &lt;td&gt;&lt;xsl:value-of select=&quot;employees/employee/name&quot;/&gt;&lt;/td&gt;
     &lt;/tr&gt;
   &lt;/table&gt;
 &lt;/body&gt;
 &lt;/html&gt;
&lt;/xsl:template&gt;
&lt;/xsl:stylesheet&gt;</pre></td></tr></table></div>

<p><b>Output</b>:</p>
<table border="1">
<tr bgcolor="#9acd32">
<th>Id</th>
<th>Name</th>
</tr>
<tr>
<td>17452</td>
<td>Jason</td>
</tr>
</table>
<p>
<b>Explanation</b>:<br />
This example does nothing much than just displaying the values of the first <b>id</b> and the <b>name</b> element encountered in the xml document. It skips the rest of <b>id</b> and the <b>name</b> elements. We can print all the missing elements using <b><xsl:for-each></b> which we will see in the next section.
</p>
<p><h3>Select every XML element</h3>
<p>The <b></b> element allows us to perform iterations in the XML document.<br />
For E.g : </p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;
&lt;xsl:stylesheet version=&quot;1.0&quot; xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot;&gt;
&lt;xsl:template match=&quot;/&quot;&gt;
 &lt;html&gt;
 &lt;body&gt;
   &lt;table border=&quot;1&quot;&gt;
     &lt;tr bgcolor=&quot;#9acd32&quot;&gt;
       &lt;th&gt;Id&lt;/th&gt;
       &lt;th&gt;Name&lt;/th&gt;
     &lt;/tr&gt;
     &lt;xsl:for-each select=&quot;employees/employee&quot;&gt;
     &lt;tr&gt;
      &lt;td&gt;&lt;xsl:value-of select=&quot;id&quot;/&gt;&lt;/td&gt;
      &lt;td&gt;&lt;xsl:value-of select=&quot;name&quot;/&gt;&lt;/td&gt;
     &lt;/tr&gt;
     &lt;/xsl:for-each&gt;
   &lt;/table&gt;
 &lt;/body&gt;
 &lt;/html&gt;
&lt;/xsl:template&gt;
&lt;/xsl:stylesheet&gt;</pre></td></tr></table></div>

<p><b>Output</b>:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<table border="1">
<tr bgcolor="#9acd32">
<th>Id</th>
<th>Name</th>
</tr>
<tr>
<td>17452</td>
<td>Jason</td>
</tr>
<tr>
<td>14782</td>
<td>Jim</td>
</tr>
<tr>
<td>12563</td>
<td>Charles</td>
</tr>
</table>
<p>
<b>Explanation</b>:<br />
In the example we can see that each of the <b><employee></b> element is iterated over and the values of the corresponding <b>id</b> and <b>name</b> elements are printed
</p>
<p><h3>Filtering the content</h3>
<p>We can filter the result generated by <b>XSLT</b>. Using filtering we can display certain content and not display others.<br />
For E.g : <br />
<xsl:for-each select="employees/employee[id='17452']">
</p>
<p><h3>Sorting the output</h3>
<p>We can sort the output generated by <b>XSLT</b> by using the <b><xsl:sort></b> element.<br />
For E.g: </p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;
&lt;xsl:stylesheet version=&quot;1.0&quot; xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot;&gt;
&lt;xsl:template match=&quot;/&quot;&gt;
&lt;html&gt;
&lt;body&gt;
	&lt;table border=&quot;1&quot;&gt;
		&lt;tr bgcolor=&quot;#9acd32&quot;&gt;
			&lt;th&gt;Id&lt;/th&gt;
			&lt;th&gt;Name&lt;/th&gt;
		&lt;/tr&gt;
		&lt;xsl:for-each select=&quot;employees/employee&quot;&gt;
		&lt;xsl:sort select=&quot;name&quot;/&gt;
		&lt;tr&gt;
			&lt;td&gt;&lt;xsl:value-of select=&quot;id&quot;/&gt;&lt;/td&gt;
			&lt;td&gt;&lt;xsl:value-of select=&quot;name&quot;/&gt;&lt;/td&gt;
		&lt;/tr&gt;
		&lt;/xsl:for-each&gt;
	&lt;/table&gt;
&lt;/body&gt;
&lt;/html&gt;
&lt;/xsl:template&gt;
&lt;/xsl:stylesheet&gt;</pre></td></tr></table></div>

<p><b>Output</b>:</p>
<table border="1">
<tr bgcolor="#9acd32">
<th>Id</th>
<th>Name</th>
</tr>
<tr>
<td>12563</td>
<td>Charles</td>
</tr>
<tr>
<td>17452</td>
<td>Jason</td>
</tr>
<tr>
<td>14782</td>
<td>Jim</td>
</tr>
</table>
<p><h3>Conditional test</h3>
<p>To test for certain condition on the content generated by <b>XSLT</b> we can use <b><xsl:if></b> element.<br />
For E.g :</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;
&lt;xsl:stylesheet version=&quot;1.0&quot; xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot;&gt;
&lt;xsl:template match=&quot;/&quot;&gt;
 &lt;html&gt;
 &lt;body&gt;
   &lt;table border=&quot;1&quot;&gt;
     &lt;tr bgcolor=&quot;#9acd32&quot;&gt;
       &lt;th&gt;Id&lt;/th&gt;
       &lt;th&gt;Name&lt;/th&gt;
     &lt;/tr&gt;
     &lt;xsl:for-each select=&quot;employees/employee&quot;&gt;
     &lt;xsl:if test=&quot;salary &gt; 45000&quot;&gt;
     &lt;tr&gt;
      &lt;td&gt;&lt;xsl:value-of select=&quot;id&quot;/&gt;&lt;/td&gt;
      &lt;td&gt;&lt;xsl:value-of select=&quot;name&quot;/&gt;&lt;/td&gt;
     &lt;/tr&gt;
     &lt;/xsl:if&gt;
     &lt;/xsl:for-each&gt;
   &lt;/table&gt;
 &lt;/body&gt;
 &lt;/html&gt;
&lt;/xsl:template&gt;
&lt;/xsl:stylesheet&gt;</pre></td></tr></table></div>

<p><b>Output</b>:</p>
<table border="1">
<tr bgcolor="#9acd32">
<th>Id</th>
<th>Name</th>
</tr>
<tr>
<td>12563</td>
<td>Charles</td>
</tr>
</table>
<p><h3>Multiple conditional tests</h3>
<p><b>XSLT</b> does not provides an If-else construct which is normally available in programming languages. However we can test for multiple conditions using a similar sort of a construct called <b><xsl:choose></b><br />
<br />
Consider the following E.g:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;
&lt;xsl:stylesheet version=&quot;1.0&quot; xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot;&gt;
&lt;xsl:template match=&quot;/&quot;&gt;
&lt;html&gt;
&lt;body&gt;
	&lt;table border=&quot;1&quot;&gt;
	&lt;tr bgcolor=&quot;#9acd32&quot;&gt;
		&lt;th&gt;Id&lt;/th&gt;
		&lt;th&gt;Name&lt;/th&gt;
	&lt;/tr&gt;
&nbsp;
	&lt;xsl:for-each select=&quot;employees/employee&quot;&gt;
	&lt;xsl:choose&gt;
	&lt;xsl:when test=&quot;salary &gt; 45000&quot;&gt;
		&lt;tr bgcolor=&quot;#F00E0E&quot;&gt;
			&lt;td&gt;&lt;xsl:value-of select=&quot;id&quot;/&gt;&lt;/td&gt;
			&lt;td&gt;&lt;xsl:value-of select=&quot;name&quot;/&gt;&lt;/td&gt;
		&lt;/tr&gt;
	&lt;/xsl:when&gt;
	&lt;xsl:otherwise&gt;
		&lt;tr bgcolor=&quot;#235CDB&quot;&gt;
			&lt;td&gt;&lt;xsl:value-of select=&quot;id&quot;/&gt;&lt;/td&gt;
			&lt;td&gt;&lt;xsl:value-of select=&quot;name&quot;/&gt;&lt;/td&gt;
		&lt;/tr&gt;
	&lt;/xsl:otherwise&gt;
	&lt;/xsl:choose&gt;
	&lt;/xsl:for-each&gt;
	&lt;/table&gt;
&lt;/body&gt;
&lt;/html&gt;
&lt;/xsl:template&gt;
&lt;/xsl:stylesheet&gt;</pre></td></tr></table></div>

<p><b>Output</b>:</p>
<table border="1">
<tr bgcolor="#9acd32">
<th>Id</th>
<th>Name</th>
</tr>
<tr bgcolor="#235CDB">
<td>17452</td>
<td>Jason</td>
</tr>
<tr bgcolor="#235CDB">
<td>14782</td>
<td>Jim</td>
</tr>
<tr bgcolor="#F00E0E">
<td>12563</td>
<td>Charles</td>
</tr>
</table>
<p>
<b>Explanation</b>:<br />
The example above explains the usage of <b><xsl:choose></b> element. Here we display employee rows in different colors based on a salary range
</p>
<p><h3>Apply Templates</h3>
<p>We can apply a template to either of these : <br />
- The root <br />
- The current element <br />
- The children of the current element </p>
<p>We can apply templates by using the <b><xsl:apply-templates></b> element. The <b><xsl:apply-templates></b> takes an attribute called <b>select</b>. If we add a select attribute, it tells XSLT processor to apply the template to the children of the element which matches the value of the select attribute. Lets look at an example : </p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;
&lt;xsl:stylesheet version=&quot;1.0&quot; xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot;&gt;
&lt;xsl:template match=&quot;/&quot;&gt;
&lt;html&gt;
&lt;body&gt;
&lt;xsl:apply-templates/&gt;
&lt;/body&gt;
&lt;/html&gt;
&lt;/xsl:template&gt;
&nbsp;
&lt;xsl:template match=&quot;employee&quot;&gt;
&lt;p&gt;
&lt;xsl:apply-templates select=&quot;name&quot;/&gt;
&lt;xsl:apply-templates select=&quot;salary&quot;/&gt;
&lt;/p&gt;
&nbsp;
&lt;/xsl:template&gt;&lt;xsl:template match=&quot;name&quot;&gt;
Name: &lt;span style=&quot;color:#ff0000&quot;&gt;
&lt;xsl:value-of select=&quot;.&quot;/&gt;&lt;/span&gt;
&nbsp;
&lt;br /&gt;
&nbsp;
&lt;/xsl:template&gt;&lt;xsl:template match=&quot;salary&quot;&gt;
Salary: &lt;span style=&quot;color:#00ff00&quot;&gt;
&lt;xsl:value-of select=&quot;.&quot;/&gt;&lt;/span&gt;
&lt;br /&gt;
&nbsp;
&lt;/xsl:template&gt;
&lt;/xsl:stylesheet&gt;</pre></td></tr></table></div>

<p><b>Output</b>:<br />
Name:<span style="color:#ff0000">Jason</span><br />
Salary:<span style="color:#00ff00">35000</span></p>
<p>Name:<span style="color:#ff0000">Jason</span><br />
Salary:<span style="color:#00ff00">35000</span></p>
<p>Name:<span style="color:#ff0000">Jason</span><br />
Salary:<span style="color:#00ff00">35000</span></p>
<p><b>Explanation</b>:<br />
The <b>xsl:apply-templates</b> in between the <b>body</b> tags declares that the template should be applied to the entire document.<br />
When an <b>employee</b> element is encountered the matched template is executed. However, inside the employee template we instruct the XSLT processor to apply template to matching <b>name</b> element and <b>salary</b> element. In the matched template we define the rules to display the current element.<br />
<br />
[<b>Note</b>: select="." refers to the current node]
</p>
<h2>XML References</h2>
<ul>
<li><a href="http://www.javabeat.net/tips/183-how-to-use-xlink-and-xpointer.html">How to use XLink and XPointer?</a></li>
<li><a href="http://www.javabeat.net/tips/182-how-to-query-xml-using-xpath.html">How to Query XML using XPath</a></li>
<li><a href="http://www.javabeat.net/tips/68-how-to-read-xml-file-and-inject-bean-referenc.html">How to read xml file and inject bean reference using Spring Framework?</a></li>
<li><a href="http://www.javabeat.net/tips/xml/1/">XML Tips</a></li>
<li><a href="http://www.javabeat.net/articles/xml/1/">XML Articles</a></li>
</ul>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2009/03/creating-xslt-documents/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>How to use XLink and XPointer?</title>
		<link>http://www.javabeat.net/2009/03/how-to-use-xlink-and-xpointer/</link>
		<comments>http://www.javabeat.net/2009/03/how-to-use-xlink-and-xpointer/#comments</comments>
		<pubDate>Thu, 12 Mar 2009 04:41:40 +0000</pubDate>
		<dc:creator>JavaBeat</dc:creator>
				<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=497</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>XLink In HTML we use anchor tags to create hyperlinks. On the same lines we can create hyperlinks in an XML document using XLink. With XLink we can define two types of link : simple and extended. Simple links are links similar to HTML links and extended links are used for linking multiple resources together. [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h3>XLink</h3>
<p>
In HTML we use anchor tags to create hyperlinks. On the same lines we can create hyperlinks in an XML document using<br />
<b>XLink</b>. With <b>XLink</b> we can define two types of link : <b>simple and extended</b>. Simple links are links similar to HTML links and extended links are used for linking multiple resources together.</p>
<h3>XPointer</h3>
<p><b>XPointer</b> allows us to navigate to specific parts of an XMl document.</p>
<h3>XLink Syntax</h3>
<p>
In HTML we have  to create a hyperlink. XML does not use any predefined tags to create hyperlinks. We can use any tag to create a hyperlink however we need to add a little bit of information to the tag to change it from a normal XML node to an XML hyperlink node. Lets look at an example: </p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;?xml version=&quot;1.0&quot;?&gt;
&lt;bookstore xmlns:xlink=&quot;http://www.w3.org/1999/xlink&quot;&gt;
	&lt;book xlink:type=&quot;simple&quot; xlink:href=&quot;http://www.lordoftherings.com&quot;&gt;Lord of the rings&lt;/homepage&gt;
	&lt;book xlink:type=&quot;simple&quot; xlink:href=&quot;http://www.harryporter.com&quot;&gt;Harry Porter&lt;/homepage&gt;
&lt;/homepages&gt;</pre></td></tr></table></div>

<p>
The most important thing to notice here is usage of the <b>xmlns</b> element. For <b>XLink</b> the namespace is <b>http://www.w3.org/1999/xlink</b>. Without this declartion we can&#8217;t use XLink in the document.</p>
<p>
Next we can see two XLink attributes : <b>xlink:type</b> and <b>xlink:href</b>. The type element refers to the type of the hyperlink (Simple or Extended) and href refers to the location to which this link should navigate to.
</p>
<h3>XPointer Syntax</h3>
<p>Sometimes it is useful to navigate to specific areas of the same page. In HTML it is possible to do this using the <b>#</b> character. In XML we can achieve the same by using <b>XPointers</b>. To navigate to a specific part of a page we need to add a pound sign <b>#</b> and a <b>XPointer</b> expression after the URL in the <b>xlink:href</b>. Lets look at an example :</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p><b>The target XML document is employees.xml</b></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;
&lt;employees&gt;
	&lt;employee id=&quot;17452&quot; vertical=&quot;banking&quot;&gt;
		&lt;id&gt;17452&lt;/id&gt;
		&lt;name&gt;Jason&lt;/name&gt;
		&lt;experience&gt;2&lt;/experience&gt;
		&lt;salary&gt;35000&lt;/salary&gt;
	&lt;/employee&gt;
&nbsp;
	&lt;employee id=&quot;14782&quot; vertical=&quot;insurance&quot;&gt;
		&lt;id&gt;14782&lt;/id&gt;
		&lt;name&gt;Jim&lt;/name&gt;
		&lt;experience&gt;3&lt;/experience&gt;
		&lt;salary&gt;45000&lt;/salary&gt;
	&lt;/employee&gt;
&nbsp;
	&lt;employee id=&quot;12563&quot; vertical=&quot;telecom&quot;&gt;
		&lt;id&gt;12563&lt;/id&gt;
		&lt;name&gt;Charles&lt;/name&gt;
		&lt;experience&gt;4&lt;/experience&gt;
		&lt;salary&gt;55000&lt;/salary&gt;
	&lt;/employee&gt;
&lt;/employees&gt;</pre></td></tr></table></div>

<p>The following XML document refers to employees in <b>employees.xml</b> using <b>xlink</b> and <b>xpointers</b></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;
&lt;myemployees xmlns:xlink=&quot;http://www.w3.org/1999/xlink&quot;&gt;
	&lt;myemployee xlink:type=&quot;simple&quot;
		xlink:href=&quot;employees.xml#14782&quot;&gt;
		&lt;description xlink:type=&quot;simple&quot;
			Jim is the employee of the year
		&lt;/description&gt;
	&lt;/myemployee&gt;
&lt;/myemployees&gt;</pre></td></tr></table></div>

<h3>Explanation</h3>
<p>In the example above we navigate to employee node with id=14782. This can be done by using either of the forms of XPointer : </p>
<ul>
<li>xlink:href=&#8221;employees.xml#xpointer(id(&#8217;14782&#8242;))&#8221; </li>
<li>xlink:href=&#8221;employees.xml#14782</li>
</ul>
<p>Both of these forms result in the same output and can be used interchangeably.</p>
<h2>XML Articles</h2>
<ul>
<li><a href="http://www.javabeat.net/tips/182-how-to-query-xml-using-xpath.html">How to Query XML using XPath?</a></li>
<li><a href="http://www.javabeat.net/tips/68-how-to-read-xml-file-and-inject-bean-referenc.html">How to read xml file and inject bean reference using Spring Framework?</a></li>
<li><a href="http://www.javabeat.net/tips/xml/1/">XML Tips</a></li>
<li><a href="http://www.javabeat.net/articles/xml/1/">XML Articles</a></li>
</li>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2009/03/how-to-use-xlink-and-xpointer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Query XML using XPath</title>
		<link>http://www.javabeat.net/2009/03/how-to-query-xml-using-xpath/</link>
		<comments>http://www.javabeat.net/2009/03/how-to-query-xml-using-xpath/#comments</comments>
		<pubDate>Thu, 12 Mar 2009 00:29:34 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=309</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>How to Query XML using XPath Introduction XML Documents are nothing until some kind of Components called Parsers parses the Documents to extract the meaningful data. Some of the most popular DOM parsers are the Simple API for XML (SAX) and Document Object Model (DOM). Both these parsers have their own advantages and disadvantages in parsing [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>How to Query XML using XPath</h2>
<h3>Introduction</h3>
<p style="text-align: justify">XML Documents are nothing until some kind of Components called Parsers parses the Documents to extract the meaningful data. Some of the most popular <strong>DOM parsers</strong> are the <strong>Simple API for XML (SAX)</strong> and <strong>Document Object Model (DOM)</strong>. Both these parsers have their own advantages and disadvantages in parsing the XML Documents. <strong>XPath</strong> is a simple Query Language for querying data from a XML Document and it is a standard specification from the W3C Group.</p>
<ul>
<li><a title="XQuery" href="http://astore.amazon.com/javabeat-20/detail/0596006349" target="_blank">XQuery</a> by Oreilly Publications.</li>
</ul>
<h3>XPath &#8211; A Query Language for XML</h3>
<p>Let us see how <strong>XPath</strong> can be used to query the various pieces of data in a XML Document. Consider a following simple XML file (employees.xml)</p>
<pre class="brush: xml; title: ; notranslate">
&lt;employees&gt;
  &lt;employee id = &quot;001&quot;&gt;
    &lt;name&gt;Johny&lt;/name&gt;
  &lt;/employee&gt;
  &lt;employee id = &quot;002&quot;&gt;
    &lt;name&gt;Williams&lt;/name&gt;
  &lt;/employee&gt;
&lt;/employees&gt;
</pre>
<p style="text-align: justify">The above XML file represents a collection of Employee instances as represented by the <strong>employee</strong> tag. A set of employees shares a common root tag <strong>employees</strong>. It is wise to mention that in XML terms a tag, element or a node all means the same. A XML Document is nothing but a collection of properly organised tags. A XML Document can contain a mixture of several of the commonly-used tags which either represent an element or the value/text stored by the element. Each element can also have certain attributes. For example, in the above employees.xml, the <strong>employees</strong>, <strong>employee</strong>, <strong>name</strong> represent the elements, the values &#8220;<strong>Williams</strong>&#8220;, &#8220;<strong>Johny</strong>&#8221; represent the text. Also note that the element/tag- employee has an &#8220;<strong>id</strong>&#8221; attribute associated with it.</p>
<p style="text-align: justify">XPath uses simple expressions to query or select a portion of information from a XML Document. For instance, if we want to get the name of the first employee, then we can frame an expression like this:</p>
<pre class="brush: xml; title: ; notranslate">
/employees/employee[1]/name
</pre>
<p>The above expression can be intepreted like this, Starting from the root of the XML Document, (which is represented by &#8220;<strong>/</strong>&#8220;) traverse until the <strong>employees</strong> element is found, then deep traverse to find the first employee element represented by employee[1], then retrive the value of the <strong>name</strong> element. As seen, the XML Document is hierarchically traversed to retrieve the information. The forward slash represents the root of the document, and multiple elements having the same name can be accessed using array based index notation. The index starts with 0, 1, … and so on. If we want to select an attribute then &#8220;<strong>@</strong>&#8221; symbol has to be prefixed along with the attribute name. For example, if we wish to query for the <strong>id</strong> value for the second employee, then the following XPath expression will just do that,</p>
<pre class="brush: xml; title: ; notranslate">
/employees/employee[2]/@id
</pre>
<h3>Java and XPath</h3>
<p>Easy to use, Java XPath API is available for accessing the XML data. The XPath API is available in the standard JDK distribution in the javax.xml.xpath package. All we have to do is to utilize the XPathFactory, XPath and XPathExpression classes and interfaces to do the task.<br />
XPathFactory class follows the standard Factory Pattern to create XPath objects. XPath objects provides an environment to compile expressions which is encapsulated by XPathExpression. Then the compiled XPathExpression can be executed to get the desired results. Following is the code snippet,</p>
<pre class="brush: java; title: ; notranslate">
XPathFactory xPathFactory = XPathFactory.newInstance();
// To get an instance of the XPathFactory object itself.
XPath xPath = xPathFactory.newXPath();
// Create an instance of XPath from the factory class.
String expression = &quot;SomeXPathExpression&quot;;
XPathExpression xPathExpression = xPath.compile(expression);
// Compile the expression to get a XPathExpression object.
Object result = xPathExpression.evaluate(xmlDocument);
// Evaluate the expression against the XML Document to get the result.
</pre>
<h3>Sample Application:</h3>
<p style="text-align: justify">Following section provides a sample application to demonstrate the usage of XPath in Java Applications. The sample application tries to select the value of an element, the value of an attribute, the value of a element-set (which is an element containing multiple elements) by compiling and executing different expressions.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<h4>projects.xml</h4>
<p>Here is a XML file called &#8216;projects.xml&#8217; which contains the structured information for various projects. The <strong>project</strong> element has an attribute called <strong>id </strong>and various nested elements like <strong>name</strong>, <strong>start-date </strong>and <strong>end-date.</strong> The structure of the XML File is given below:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;xml version=&quot;1.0&quot; encoding=&quot;UTF-8&gt;
&lt;projects&gt;
  &lt;project id = &quot;BP001&quot;&gt;
    &lt;name&gt;Banking Project&lt;/name&gt;
    &lt;start-date&gt;Jan 10 1999&lt;/start-date&gt;
    &lt;end-date&gt;Jan 10 2003&lt;/end-date&gt;
  &lt;/project&gt;
  &lt;project id = &quot;TP001&quot;&gt;
    &lt;name&gt;Telecommunication Project&lt;/name&gt;
    &lt;start-date&gt;March 20, 1999&lt;/start-date&gt;
    &lt;end-date&gt;July 30, 2004&lt;/end-date&gt;
  &lt;/project&gt;
  &lt;project id = &quot;PP001&quot;&gt;
    &lt;name&gt;Portal Project&lt;/name&gt;
    &lt;start-date&gt;Dec 10 1999&lt;/start-date&gt;
    &lt;end-date&gt;March 10 2006&lt;/end-date&gt;
  &lt;/project&gt;
&lt;/projects&gt;
</pre>
<p>XPathReader.java</p>
<p>Now, let write a simple Java Application which acts as a reader in reading the various pieces of information from the XML Document. Following is the Java source that does the job of parsing the XML Document:</p>
<pre class="brush: java; title: ; notranslate">
import java.io.IOException;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class XPathReader {

  private String xmlFile;
  private Document xmlDocument;
  private XPath xPath;

  public XPathReader(String xmlFile) {
    this.xmlFile = xmlFile;
    initObjects();
  }

  private void initObjects(){
      try {
        xmlDocument = DocumentBuilderFactory.
        newInstance().newDocumentBuilder().
        parse(xmlFile);
        xPath =  XPathFactory.newInstance().
        newXPath();
      } catch (IOException ex) {
        ex.printStackTrace();
      } catch (SAXException ex) {
        ex.printStackTrace();
      } catch (ParserConfigurationException ex) {
        ex.printStackTrace();
      }
  }

  public Object read(String expression, QName returnType){
    try {
      XPathExpression xPathExpression =
      xPath.compile(expression);
      return xPathExpression.evaluate
      (xmlDocument, returnType);
    } catch (XPathExpressionException ex) {
      ex.printStackTrace();
      return null;
    }
  }
}
</pre>
<p>The constructor of this class is passed a XML File from which the information has to be read. The method initObjects() is called immediately, and it is used to initialize the XML Document and the XPath objects. A Document representation of the XML File is created by calling the DocumentBuilder.parse() method Then, a new XPath object is created by calling the XPathFactory.newXPath() method.</p>
<p>Client Applications can then call XPathReader.read() method by passing the expression to be evaluated and the return type of the expression. The return type of the expression is a QName which in XML terms, stands for Qualified Name. The standard XPath data-types are String, Number, Boolean, Node, NodeSet etc., which are represented as constants in XPathConstants namely XPathConstants.STRING, XPathConstants.NUMBER, XPathConstants.BOOLEAN, XPathConstants.NODE and XPathConstants.NODESET. Hence, the return type after evaluating an expression should be any of the above mentioned data-types. Within the read() method, an expression is compiled using the XPath.compile() method which returns a XPathExpression and the compiled expression can be evaluated using XPathExpression.evaluate() method.</p>
<p>XPathReaderTest.java</p>
<pre class="brush: java; title: ; notranslate">
package com.javabeat.tips.xpath;
import javax.xml.xpath.XPathConstants;
import org.w3c.dom.*;
public class XPathReaderTest {

  public XPathReaderTest() {
  }

  public static void main(String[] args){

      XPathReader reader = new XPathReader(&quot;
      src\com\javabeat\tips\xpath\projects.xml&quot;);

      // To get a xml attribute.
      String expression = &quot;/projects/project[1]/@id&quot;;
      System.out.println(reader.read(expression,
      XPathConstants.STRING) + &quot;n&quot;);

      // To get a child element's value.'
      expression = &quot;/projects/project[2]/name&quot;;
      System.out.println(reader.read(expression,
      XPathConstants.STRING) + &quot;n&quot;);

      // To get an entire node
      expression = &quot;/projects/project[3]&quot;;
      NodeList thirdProject = (NodeList)reader.read(expression,
      XPathConstants.NODESET);
      traverse(thirdProject);
    }

  private static void traverse(NodeList rootNode){
    for(int index = 0; index &amp;lt; rootNode.getLength(); index ++){
      Node aNode = rootNode.item(index);
      if (aNode.getNodeType() == Node.ELEMENT_NODE){
        NodeList childNodes = aNode.getChildNodes();
        if (childNodes.getLength() &amp;gt; 0){
          System.out.println(&quot;Node Name--&amp;gt;&quot; +
          aNode.getNodeName() +
          &quot; , Node Value--&amp;gt;&quot; +
          aNode.getTextContent());
        }
        traverse(aNode.getChildNodes());
      }
    }
  }
}
</pre>
<p>This test application uses the XPathReader class by creating its instance and then calls the XPathReader.read() method by passing different expressions and return types. As we see, the third expression tries to retrieve an entire node-set by passing the return type as XPathConstants.NODESET. Since a node-set contains a collection of nodes which in turn can contain some other nodes, a Recursive Traversal is made on the node-set to get the name and the value of the node by calling the Node.getNodeName() and Node.getTextContent() methods. The following would be the expected output for the above sample client application.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2009/03/how-to-query-xml-using-xpath/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>XQuery Syntax</title>
		<link>http://www.javabeat.net/2009/03/xquery-syntax/</link>
		<comments>http://www.javabeat.net/2009/03/xquery-syntax/#comments</comments>
		<pubDate>Thu, 05 Mar 2009 04:40:54 +0000</pubDate>
		<dc:creator>JavaBeat</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=495</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>XQuery is a concept very similar to SQL. As sql is used to query database tables we can use XQuery to query XML data. Xquery can be used to query XML documents, data which is in XML syntax and databases. Using XQuery we can find XML elements. This can be very useful in situations when [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><b>XQuery</b> is a concept very similar to SQL. As sql is used to query database tables we can use <b>XQuery</b> to query XML data. <b>Xquery</b> can be used to query XML documents, data which is in XML syntax and databases. Using <b>XQuery</b> we can find XML elements. This can be very useful in situations when we need to search relevant information in large XML documents or XML data. Using <b>XQuery</b> we can exactly extract informatiuon what we are really looking for. <b>XQuery</b> is a W3C standards.
</p>
<p>
We will be using the following document to understand the basic of XQuery: </p>
<p>File Name : <b>employees.xml</b></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;
&lt;employees&gt;
	&lt;employee vertical=&quot;banking&quot;&gt;
		&lt;id&gt;17452&lt;/id&gt;
		&lt;name&gt;Jason&lt;/name&gt;
		&lt;experience&gt;2&lt;/experience&gt;
		&lt;salary&gt;35000&lt;/salary&gt;
	&lt;/employee&gt;
&nbsp;
	&lt;employee vertical=&quot;insurance&quot;&gt;
		&lt;id&gt;14782&lt;/id&gt;
		&lt;name&gt;Jim&lt;/name&gt;
		&lt;experience&gt;3&lt;/experience&gt;
		&lt;salary&gt;45000&lt;/salary&gt;
	&lt;/employee&gt;
&nbsp;
	&lt;employee vertical=&quot;telecom&quot;&gt;
		&lt;id&gt;12563&lt;/id&gt;
		&lt;name&gt;Charles&lt;/name&gt;
		&lt;experience&gt;4&lt;/experience&gt;
		&lt;salary&gt;55000&lt;/salary&gt;
	&lt;/employee&gt;
&lt;/employees&gt;</pre></td></tr></table></div>

<h2>Selecting nodes in XQuery</h2>
<h3>Functions</h3>
<p>
XQuery uses the <b>doc</b> function to open a XML document.<br />
E.g : doc(&#8220;employees.xml&#8221;)
</p>
<h3>Path Expressions</h3>
<p>XQuery uses <b>path</b> expressions to traverse a XML document.</p>
<p>E.g: doc(&#8220;employees.xml&#8221;)/employees/employee/name</p>
<p>The above XQuery produces the following output :</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;name&gt;Jason&lt;/name&gt;
&lt;name&gt;Jim&lt;/name&gt;
&lt;name&gt;Charles&lt;/name&gt;</pre></td></tr></table></div>

</p>
<h3>Predicates</h3>
<p>Predicates are used in <b>XQuery</b> to filter data from a XML document.</p>
<p>E.g: doc(&#8220;employees.xml&#8221;)/employees/employee[salary>45000]</p>
<p>The above <b>XQuery</b> produces the following output :</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;employee vertical=&quot;telecom&quot;&gt;
	&lt;id&gt;12563&lt;/id&gt;
	&lt;name&gt;Charles&lt;/name&gt;
	&lt;experience&gt;4&lt;/experience&gt;
	&lt;salary&gt;55000&lt;/salary&gt;
&lt;/employee&gt;</pre></td></tr></table></div>

</p>
<h3>FLWOR</h3>
<p>FLWOR can be expanded to &#8220;For, Let, Where, Order by, Return&#8221;. Consider this example :</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">for $x in doc(&quot;employees.xml&quot;)/employees/employee
where $x/salary&gt;35000
order by $x/name
return $x/name</pre></td></tr></table></div>

</p>
<h3>Output</h3>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;name&gt;Jim&lt;/name&gt;
&lt;name&gt;Charles&lt;/name&gt;</pre></td></tr></table></div>

</p>
<h2>Explanation</h2>
<p>In the above example :</p>
<ul>
<li>The <b>for</b> clause selects all employee elements under employees element into the variable $x</li>
<li>The <b>where</b> clause selects only those employees whose salary is greater than 35000</li>
<li>The <b>order</b> by clause determines the sort order based on a named columm</li>
<li>The <b>return</b> clause determines what value should be returned. Here the name of employees is returned</li>
</ul>
<h2>If-Else construct in XQuery</h2>
<p>
It is possible to write the <b>IF-Else</b> construct in XQuery using the following syntax:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">for $x in doc(&quot;employees.xml&quot;)/employees/employee
return if($x/salary gt 35000)
then &lt;senior&gt;{data($x/name)}&lt;/senior&gt;
else &lt;junior&gt;{data($x/name)}&lt;/junior&gt;</pre></td></tr></table></div>

<p>[<b>Note</b> : The function <b>data</b> is used to extract the value of a node]
</p>
<h3>Output</h3>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">	&lt;junior&gt;Jason&lt;/junior&gt;
	&lt;senior&gt;Jim&lt;/senior&gt;
	&lt;senior&gt;Charles&lt;/senior&gt;</pre></td></tr></table></div>

</p>
<h2>XQuery Comparisons</h2>
<p>We can do comparison in XQuery by using two set of operators :</p>
<ul>
<li>1) <b>General comparision operators</b>: =, !=, <, , >= </li>
<li>2) <b>Value comparision operators</b>: eq, ne, lt, le, gt, ge </li>
</ul>
<p>The difference between these two is that the General Operators works for multiple set of values while Value comparision works for a single value</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2009/03/xquery-syntax/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What is RSS and Atom?</title>
		<link>http://www.javabeat.net/2008/12/what-is-rss-and-atom/</link>
		<comments>http://www.javabeat.net/2008/12/what-is-rss-and-atom/#comments</comments>
		<pubDate>Fri, 19 Dec 2008 15:18:48 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=2234</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>About this book RSS and Atom are the most widely used of many content syndication formats that have developed over the last few years to address the need to distribute and receive streams of content from websites and applications. Sites syndicate content for a broad variety of reasons, from replacing email as a medium for [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>About this book</h2>
<p>
<b><i>RSS and Atom</i></b> are the most widely used of many content syndication formats that have developed over the last few years to address the need to distribute and receive streams of content from websites and applications. Sites syndicate content for a broad variety of reasons, from replacing email as a medium for outbound contact to updating satellite sites. Each format has </p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2008/12/what-is-rss-and-atom/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Writing simple ANT build script</title>
		<link>http://www.javabeat.net/2008/07/writing-simple-ant-build-script/</link>
		<comments>http://www.javabeat.net/2008/07/writing-simple-ant-build-script/#comments</comments>
		<pubDate>Thu, 24 Jul 2008 10:54:33 +0000</pubDate>
		<dc:creator>JavaBeat</dc:creator>
				<category><![CDATA[ANT]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=188</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Apache Ant Example This article explains how to write a very basic ANT build script. This does not explain indepth knowledge on building your project using ANT script. But, this writeup will be more useful for the beginners who haben&#8217;t writen any ANT script before. Before start writing the script, lets look into how to [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h1>Apache Ant Example</h1>
<p>This article explains how to write a very basic <b><i>ANT</i></b> build script. This does not explain indepth knowledge on building your project using <b><i>ANT script</i></b>. But, this writeup will be more useful for the beginners who haben&#8217;t writen any  <b><i>ANT</i></b> script before. Before start writing the script, lets look into how to install the <b><i>ANT</i></b> in your machine.</p>
<h1>Install Apache Ant</h1>
<p>Download the <b><i>Apache Ant</i></b> from the link : <a href="http://ant.apache.org/bindownload.cgi">Download Apache Ant</a></p>
<ul>
<li>Unzip the files into your machine.</li>
<li>Set your system path variable to ANT&#8217;s bin directory. For example d:/projects/ant/bin&#8221;</li>
<li>Set the <b><i>ANT_HOME</i></b> in your system variables. <b><i>ANT_HOME</i></b> should point to your Ant installation directory. For example &#8220;d:/projects/ant&#8221;.</li>
<li>Set <b><i>JAVA_HOME</i></b> in your system environment variables.</li>
<li>Copy <b><i>tools.jar</i></b> file into the &#8220;JRE/lib&#8221; folder.</li>
</ul>
<p>	To test the setup open your command prompt and type as &#8220;ant&#8221;. You will see a message saying</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">Buildfile: build.xml does not exist!
Build failed</pre></td></tr></table></div>

<p>Set up is done. Let&#8217;s look into our first simple example program using <b><i>ANT</i></b> script.
</p>
<p>This example program shows how to create the <b><i>JAR</i></b> file after building all the java files.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;project name=&quot;sampleProject&quot; basedir=&quot;.&quot; default=&quot;jar&quot;&gt;</pre></td></tr></table></div>

<p>In the above code &#8220;sampleProject&#8221; is the project name for this prticular build. We are setting base directory as the current directory by just giving .(dot). We are telling the script to start from &#8220;jar&#8221; target name.	The <b><i>default</i></b> attribute is used for setting the starting point for the ANT script.</p>
<p>We call a seperate task as <b><i>target</i></b>. We can define as many number of targets inside a build file. If we closely look into the build file, we have many number of targets based its operations. So, our build starts with &#8220;jar&#8221; <b><i>target</i></b>.</p>
<p>Target has <b><i>depends</i></b> attribute to indicate, that particular task can be executed only after the certain number of dependencies. In our case, before building the jar file, we have to compile the files. So, jar target calls compile target. That has some dependencies that is executed. Once the build is successful, test.jar will be created in the same directory. </p>
<h4>build.xml</h4>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;?xml version=&quot;1.0&quot;?&gt;
&lt;project name=&quot;sampleProject&quot; basedir=&quot;.&quot; default=&quot;jar&quot;&gt;
    &lt;property name=&quot;src&quot; value=&quot;ant-source&quot;/&gt;
    &lt;property name=&quot;output&quot; value=&quot;bin&quot;/&gt;
&nbsp;
    &lt;target name=&quot;compile&quot; depends=&quot;create&quot;&gt;
        &lt;javac destdir=&quot;bin&quot;&gt;
            &lt;src path=&quot;${src}&quot;/&gt;
            &lt;classpath refid=&quot;java&quot;/&gt;
        &lt;/javac&gt;
    &lt;/target&gt;
&nbsp;
    &lt;target name=&quot;jar&quot; depends=&quot;compile&quot;&gt;
        &lt;jar destfile=&quot;test.jar&quot;&gt;
            &lt;fileset dir=&quot;bin&quot;/&gt;
        &lt;/jar&gt;
    &lt;/target&gt;
&nbsp;
&nbsp;
    &lt;target name=&quot;clean&quot;&gt;
        &lt;delete dir=&quot;${output}&quot;/&gt;
    &lt;/target&gt;
&nbsp;
    &lt;target name=&quot;create&quot; depends=&quot;clean&quot;&gt;
        &lt;mkdir dir=&quot;${output}&quot;/&gt;
    &lt;/target&gt;
&nbsp;
    &lt;path id=&quot;java&quot;&gt;
        &lt;fileset dir=&quot;D:JarsHibernate&quot;&gt;
            &lt;include name=&quot;*.jar&quot;/&gt;
        &lt;/fileset&gt;
    &lt;/path&gt;
&lt;/project&gt;</pre></td></tr></table></div>

<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2008/07/writing-simple-ant-build-script/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
