JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy
  • Contact Us

Use Trang to Generate XSD from XML File

November 5, 2013 by Krishna Srinivasan Leave a Comment

XML schema used for defining the restriction on XML data structure. It is adding the highly validated data structure and useful for defining the types for the data in XML files. In a normal practice, first a developer creates a XSD (schema) with validations or enforcement for the XML structure, later all the XML files created will use that XSD for validating the rules. In some scenarios, we have a valid XML file and we need to create a schema file for that XML structure. This tutorial explains how to create a XSD file using existing XML file. We will use a tool called trang for achieving this.

Download Trang

It is an open source API for working with XML files. One of the functionality it offers is to generate a XSD file using XML file. You can download the JAR file from here.

[code]
//java -jar <trang JAR file path> <XML file name> <XSD file name>
java -jar D:/trang.jar Sample.xml Sample.xsd
[/code]

I have used the below sample XML and XSD files for this tutorial. If you have any questions, please write it in the comments section.

XML File

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<company>
<branch>
<employee id="001">
<name>Name 1</name>
<designation>Engineer</designation>
</employee>
<employee id="002">
<name>Name 2</name>
<designation>Engineer</designation>
</employee>
</branch>
</company>
[/code]

Generate XML Schema

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xs:element name="company">
<xs:complexType>
<xs:sequence>
<xs:element ref="branch"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="branch">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" ref="employee"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="employee">
<xs:complexType>
<xs:sequence>
<xs:element ref="name"/>
<xs:element ref="designation"/>
</xs:sequence>
<xs:attribute name="id" use="required" type="xs:integer"/>
</xs:complexType>
</xs:element>
<xs:element name="name" type="xs:string"/>
<xs:element name="designation" type="xs:NCName"/>
</xs:schema>
[/code]

Filed Under: XML Tagged With: XML Schema

How To Convert Properties File Into XML File Using Java?

October 27, 2013 by Krishna Srinivasan Leave a Comment

In my previous tutorials I have explained about how to use DOM Parser and SAX Parser. This tutorial explain with very simple utility method available in the Java package used for converting your existing properties file to a XML file. Sometimes this may be the requirement for Java developers, instead of manually converting properties file to XML, you can use this simple utility class to input the properties file and get the result in the XML file. This utility available in the java.util.Properties and the method name is storeToXML(). Look at the below example.

1. Create A Simple Properties File

[code]
key1=Message1
key2=Message2
key3=Message3
[/code]

2. Write Utility For Conversion

PropToXmlDemo.java

[code lang=”java”]
package javabeat.net.xml;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

public class PropToXmlDemo {
public static void main(String[] args) throws IOException
{
Properties props = new Properties();
try{
props.load(PropToXmlDemo.class.getClassLoader().getResourceAsStream("javabeat/net/xml/messages.properties"));
}catch (Exception e){
e.printStackTrace();
}
//Path for the output file
File file = new File("msg.xml");
file.createNewFile();
OutputStream out = new FileOutputStream(file);
//Call the utility method to store the properties values to XML file
props.storeToXML(out, "Message Properties","UTF-8");
}

}
[/code]

3. Outout XML File

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Message Properties</comment>
<entry key="key3">Message3</entry>
<entry key="key2">Message2</entry>
<entry key="key1">Message1</entry>
</properties>

[/code]

4. Folder Structure

Look at the folder structure for the above example.

Properties To XML File Folder Structure

If you have any questions, please write it in the comments section.

Filed Under: XML Tagged With: XML

How to Parse XML file using SAX Parser?

October 27, 2013 by Krishna Srinivasan Leave a Comment

In my previous article I had written the example program for parsing a simple XML file using the DOM parser. As I have mentioned in the earlier posts, DOM and SAX are the two popular parser used for reading and manipulating the XML files. If you use any of the XML utility like JAXB for Java / XML binding, they are internally using any of these parser. DOM and SAX are the core APIs for reading the XML files. Both are working in the different way.

  1. DOM loads the entire XML file into meorty and then retrives the XML elements. It is good for the small XML files. If the XML file is huge in size, it will impact the performance and consumes lot of memory.
  2. SAX parser uses the event driven model to find an element. It traverses the entire XML file to find the elements.  SAX parser is faster and less memory then a DOM parser.

SAX uses the callback functions the class org.xml.sax.helpers.DefaultHandler for reading the XML elements. The following are the callback functions:

  1. startDocument and endDocument: This mthods are are called at the start and end of the document.
  2. startElement and endElement: This methods are called at the time when parser reading the start tag and end tag for each elements.
  3. characters: This method is called when it finds text content inside the start and end tag of an element.

Look at the example. Before that look how the folder structure for this example is setup. Keep the XML at the root of the project directory.

XML SAX Parser

1. Create A Simple XML File

employee.xml

[code lang=”xml”]
<?xml version="1.0"?>
<company>
<employee id="001">
<firstname>Krishna</firstname>
<lastname>Srinivasn</lastname>
</employee>
<employee id="002">
<firstname>Muthu</firstname>
<lastname>Kumar</lastname>
</employee>
</company>
[/code]

2. SAX Parser For Parsing The XML File

JavaSAXParser.java

[code lang=”java”]
package javabeat.net.xml;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class JavaSAXParser extends DefaultHandler {
public static void main(String args[]) {
JavaSAXParser xmlParser = new JavaSAXParser();
xmlParser.parseXmlUsingSAX();
}

public void parseXmlUsingSAX() {
try {
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
SAXParser saxParser = saxParserFactory.newSAXParser();
DefaultHandler defaultHandler = new DefaultHandler() {
String firstNameTag = "close";
String lastNameTag = "close";

public void startElement(String uri, String localName,
String qName, Attributes attributes)
throws SAXException {

if (qName.equalsIgnoreCase("FirstName")) {
firstNameTag = "open";
}
if (qName.equalsIgnoreCase("lastName")) {
lastNameTag = "open";
}
}

public void characters(char ch[], int start, int length)
throws SAXException {

if (firstNameTag.equals("open")) {
System.out.println("First Name : "
+ new String(ch, start, length));
}
if (lastNameTag.equals("open")) {
System.out.println("Last Name : "
+ new String(ch, start, length));
}
}

public void endElement(String uri, String localName,
String qName) throws SAXException {

if (qName.equalsIgnoreCase("firstName")) {
firstNameTag = "close";
}
if (qName.equalsIgnoreCase("lastName")) {
lastNameTag = "close";
}
}
};
saxParser.parse("employees.xml", defaultHandler);
} catch (Exception e) {
e.printStackTrace();
}
}
}

[/code]

The output for the above program will be:

SAX Parser Output

I hope the above example helped you to understand the SAX implementation. If you have any questions, please write it in the comments section.

Filed Under: XML Tagged With: XML

How to Parse XML file using DOM Parser?

October 26, 2013 by Krishna Srinivasan Leave a Comment

In this tutorial I will write a simple example program for parsing a XML file using the DOM parser. DOM parser reads the entire XML file and loads into the memory. It forms a tree structure in the memory and returns the element details when queried. It is the faster when comparing to the SAX parser. But, it consumes huge memory when the XML file is large in size. DOM parser is very good choice when the XML file size is relatively small and memory is not an issue for the performance.

If the XML is huge, choose SAX parser which will be faster and consumes less memory.

employee.xml

[code lang=”xml”]
<?xml version="1.0"?>
<company>
<employee id="001">
<firstname>Krishna</firstname>
<lastname>Srinivasn</lastname>
</employee>
<employee id="002">
<firstname>Muthu</firstname>
<lastname>Kumar</lastname>
</employee>
</company>
[/code]

JavaDOMParser.java

[code lang=”java”]
package javabeat.net.xml;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;

public class JavaDOMParser {
public static void main(String argv[]) {
try {
File xmlFilePath = new File("employees.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(xmlFilePath);
doc.getDocumentElement().normalize();
System.out.println("Root element :"
+ doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("employee");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Employee Id : "
+ eElement.getAttribute("id"));
System.out.println("First Name : "
+ eElement.getElementsByTagName("firstname")
.item(0).getTextContent());
System.out.println("Last Name : "
+ eElement.getElementsByTagName("lastname").item(0)
.getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

[/code]

Output for this program will be:

[code]
Root element :company
Employee Id : 001
First Name : Krishna
Last Name : Srinivasn
Employee Id : 002
First Name : Muthu
Last Name : Kumar

[/code]

Filed Under: XML Tagged With: XML

Generate XSD from XML files

April 12, 2012 by Krishna Srinivasan Leave a Comment

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.

also read:

  • XML Tutorials
  • How to Parse XML file using DOM Parser?
  • How to Parse XML file using SAX Parser?

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’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.

  • How to Convert XML to Xsd Online
  • XML-2-XSD
  • List of Links

If you are facing any issues on converting the XML files into the XSD, please post it here.

Filed Under: XML Tagged With: XML, XSD

JAXB Exception : nor any of its super class is known to this context

April 3, 2012 by Krishna Srinivasan Leave a Comment

When you are working with the JAXB objects, there are some times you would encounter the exception saying the “nor any of its super class is known to this context”. The reason for this error could be many reasons it depends on the environment you are working. The simple solution for fixing the problem is to add

also read:

  • XML Tutorials
  • How to Parse XML file using DOM Parser?
  • How to Parse XML file using SAX Parser?

[code lang=”java”]
@XmlSeeAlso({ClassName.class})
[/code]
When you are working with the JAXB objects, there are some times you would encounter the exception saying the “nor any of its super class is known to this context”. The reason for this error could be many reasons it depends on the environment you are working. The simple solution for fixing the problem is to add
[code lang=”java”]
@XmlSeeAlso({ClassName.class})
[/code]

element in all the classes generated by the JAXB generator. For example, if you are trying to marshall the java object into the XML file using the following code:
[code lang=”java”]
JAXBContext jaxbContext = JAXBContext     .newInstance("com.request");

   Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

   // output pretty printed

   jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

   RequestClass request = new RequestClass();

   jaxbMarshaller.marshal(requestClass, file);
[/code]
The XML file will be generated base don the RequestClass. All the other files would have to add the @XmlSeeAlso({RequestClass.class}) to avoid this exception. It is only the work around and not the fixed solution for this problem.
element in all the classes generated by the JAXB generator. For example, if you are trying to marshall the java object into the XML file using the following code:
[code lang=”java”]
JAXBContext jaxbContext = JAXBContext     .newInstance("com.request");

   Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

   // output pretty printed

   jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

   RequestClass request = new RequestClass();

   jaxbMarshaller.marshal(requestClass, file);
[/code]
The XML file will be generated base don the RequestClass. All the other files would have to add the @XmlSeeAlso({RequestClass.class}) to avoid this exception. It is only the work around and not the fixed solution for this problem.

Filed Under: XML Tagged With: JAXB

What is XPath?

April 3, 2009 by Krishna Srinivasan Leave a Comment

Processing XML documents with Oracle JDeveloper 11g

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

also read:

  • XML Tutorials
  • How to Parse XML file using DOM Parser?
  • How to Parse XML file using SAX Parser?

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

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

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

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

What This Book Covers

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

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

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

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

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

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

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

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

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

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

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

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

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

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

What is XPath?

As mentioned in the earlier chapters, XML documents can be used for the transfer of data. The data in an XML document may be retrieved either with the JAXP (Java API for XML Processing) DOM and SAX APIs, or with the JAXP XPath API. Addressing
an XML document with XPath has the advantage that a single node may be selected directly without iterating over a node set. With SAX and DOM APIs, node lists have to be iterated over to access a particular node. Another advantage of navigating an XML document with XPath is that an attribute node may be selected directly. With DOM and SAX APIs, an element node has to be selected before an element attribute can be selected. In this chapter we shall discuss XPath support in JDeveloper.

What is XPath?

XPath is a language for addressing an XML document’s elements and attributes. As an example, say you receive an XML document that contains the details of a shipment and you want to retrieve the element/attribute values from the XML document. You don’t just want to list the values of all the nodes, but also want to output the values of specific elements or attributes. In such a case, you would use
XPath to retrieve the values of those elements and attributes. XPath constructs a hierarchical structure of an XML document, a tree of nodes, which is the XPath data model. The XPath data model consists of seven node types. The different types of nodes in the XPath data model are discussed in the following table:

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

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

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

An example of a location step is:

[code lang=”java”] child::journal[position()=2]
[/code]

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

XPath support in Oracle XDK 11g

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

In this chapter we shall parse an example XML document with the DOMParser class, obtain an XMLDocument object for the XML document, and select nodes from the document with the XMLDocument class select methods. The different select methods in the XMLDocument class are discussed in the following table:

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

The example XML document that is parsed in this chapter has a namespace declaration mlns:journal=”http://www.xdk11g.com/xpath” for elements in the namespace with the prefix journal. For an introduction on namespaces in XML refer to the W3C Recommendation on Namespaces in XML 1.0 (http://www.w3.org/ TR/REC-xml-names/). catalog.xml, the example XML document, is shown in the
following listing:

[code lang=”java”]&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;
[/code]

Setting the environment

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

To develop an application with XPath, add the required libraries to the project classpath. Select the project node in Application Navigator and select Tools|Project Properties. In the Project Properties window, select the Libraries and Classpath node. To add a library, select the Add Library button. Select the Oracle XML Parser v2 library. Click on the OK button in the Project Properties window. We also need to add an XML document that is to be parsed and navigated with XPath.

To add an XML document, select File|New. In the New Gallery window, select Categories|General|XML and Items|XML Document. Click on the OK button. In the Create XML File window specify the file name catalog.xml in the File Name field, and click on the OK button. Copy the catalog.xml listing to the catalog.xml file in the Application Navigator. The directory structure of the XPath project is shown in the following illustration:

xpath-1

XPath search

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

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

xpath-2

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

xpath-3

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

Selecting nodes with absolute location paths

Nex t, we shall demonstrate with various examples of selecting nodes using XPath. As an example, select all the title elements in catalog.xml. Specify the XPath expression for selecting the title elements in the Expression field of the Apply an XPath Expression on catalog.xml window. The XPath expression to select all title elements is /catalog/journal/article/title. Click on the OK button to select the title elements.

xpath-4

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

xpath-5

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

xpath-6

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

xpath-7

Attribu te nodes may also be selected with XPath. Attributes are selected by using the “@” prefix. As an example, select the section attribute in the first article element in the journal element. The XPath expression for selecting the section attribute is
/catalog/journal/article[1]/@section and is specified in the Expression field. Click on the OK button to select the section attribute.

xpath-8

The attr ibute section gets outputted in JDeveloper.

xpath-9

Selecting nodes with relative location paths

In the pr evious examples, an absolute location is used to select nodes. Next, we shall demonstrate selecting an element with a relative location path. As an example, select the title of the first article element in the journal element. The relative location path for selecting the title element is child::catalog/journal/article[position()=1]/ title. Specifying the axis as child and node test as catalog selects all the child nodes of the catalog node and is equivalent to an absolute location path that starts with /catalog. If the child nodes of the journal node were required to be selected, specify the node test as journal. Specify the XPath expression in the Expression
field and click on the OK button.

xpath-10

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

xpath-11

Selecting namespace nodes

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

xpath-12

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

Attributes in a namespace may also be selected with XPath Search. As an example, select the section attributes in the journal namespace. Specify the XPath expression to select the section attributes in the Expression field and click on the OK button.

Section attributes in the journal namespace get selected.

Selecting nodes with XPath API

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

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

[code lang=”java”] import oracle.xml.parser.v2.*;
[/code]

Creating the DOM parser

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

[code lang=”java”] DOMParser domParser=new DOMParser();[/code]

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

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

[code lang=”java”] domParser.parse(new FileReader(xmlDocument));[/code]

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.

[code lang=”java”] XMLDocument document=domParser.getDocument();[/code]

Method selectS ingleNode(String)

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

[code lang=”java”] XMLNode titleNode=(XMLNode)document.selectSingleNode(&quot;/catalog/
journal/article[@section=’ORACLE DEVELOPER’]/title&quot;);
[/code]

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:

[code lang=”java”] String title=titleNode.getFirstChild().getNodeValue();
[/code]

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

[code lang=”java”] XMLNode authorNode=(XMLNode)document.selectSingleNode(&quot;/catalog/
journal/article[title= Oracle Database 11g Redux’]/author&quot;);
[/code]

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:

[code lang=”java”] String author=authorNode.getFirstChild().getNodeValue();
[/code]

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:

[code lang=”java”] XMLNode sectionNode=(XMLNode)document.selectSingleNode(&quot;/catalog/
journal[@date=March-April 2008]/article[2]/@section&quot;);
[/code]

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

[code lang=”java”] String section=sectionNode.getNodeValue();
[/code]

Method selectNodes(String)

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

[code lang=”java”] NodeList nodeList=document.selectNodes(&quot;/catalog/journal[@date=’March-
April 2008′]/article/title&quot;);
[/code]

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

[code lang=”java”] for(int i=0; i&lt;nodeList.getLength(); i++){
titleNode=(XMLElement)nodeList.item(i);
title=titleNode.getFirstChild().getNodeValue();
System.out.println(title);
}
[/code]

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:

[code lang=”java”] NodeList
nodeList=document.selectNodes(&quot;/catalog/journal[@date=’March- April
2008]/article/@section&quot;);
[/code]

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

[code lang=”java”] 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;);
}
[/code]

Method selectSingleNode(String,NSResolver)

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

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

[code lang=”java”] 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;);
}
}
}
[/code]

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

[code lang=”java”] CustomNSResolver resolver=new CustomNSResolver();
resolver.resolveNamespacePrefix(&quot;journal&quot;);
[/code]

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:

[code lang=”java”] XMLNode sectionNode= (XMLNode)document.selectSingleNode(&quot;/catalog/
journal:journal/journal:article/@journal:section&quot;, resolver);
section=sectionNode.getNodeValue();
[/code]

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

[code lang=”java”] XSLException Namespace prefix ‘journal’ used but not declared.
[/code]

Method selectNodes(String,NSResolver)

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

[code lang=”java”] NodeList nodeList=document.selectNodes(&quot;/catalog/journal:journal[@
journal:date=’November-December 2008′]/journal:article/title&quot;,
resolver );
[/code]

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.

[code lang=”java”] for(int i=0; i&lt;nodeList.getLength(); i++){
titleNode=(XMLElement)nodeList.item(i);
title=titleNode.getFirstChild().getNodeValue();
System.out.println(title);
}
[/code]

Running the Java application

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

  1. First, we import the required packages from XDK 11g.
    [code lang=”java”] import oracle.xml.parser.v2.*;
    import java.io.*;
    import org.xml.sax.SAXException;
    import org.w3c.dom.*;
    [/code]
  2. Next, we add the XPathParser Java class declaration.
    [code lang=”java”] public class XPathParser{
    [/code]
  3. We define the parseDocument method to parse an XML document with the DOMParser.
  4. [code lang=”java”] public void parseDocument(File xmlDocument){
    try{
    [/code]

  5. Next, we create a DOMParser object and parse the XML document.
    [code lang=”java”] DOMParser domParser=new DOMParser();
    domParser.parse(new FileReader(xmlDocument));
    XMLDocument document=domParser.getDocument();
    [/code]
  6. We specify the NSResolver object to resolve namespaces.
    [code lang=”java”] CustomResolver resolver=new CustomResolver();
    resolver.resolveNamespacePrefix(&quot;journal&quot;);
    [/code]
  7. Next, we select nodes using the selectSingleNode(String) method.
    [code lang=”java”] 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);
    [/code]
  8. We select nodes using the selectNodes(String) method.
    [code lang=”java”] 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;);
    }
    [/code]
  9. Next, we select nodes using the selectSingleNode(String,NSResolver) method.
    [code lang=”java”]
    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;);
    [/code]
  10. We also select nodes using the selectNodes(String,NSResolver) method.
    [code lang=”java”] 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());
    }
    }
    [/code]
  11. We add the Java class that extends the NSResolver class.
    [code lang=”java”] 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;
    }
    }
    [/code]
  12. Finally, we define the main method in which we create an instance of the
    [code lang=”java”] 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;));
    }
    }
    [/code]

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

Summary

In this chapter you learned about XPath support in JDeveloper 11g. JDeveloper provides an XPath Search GUI tool to select nodes from an XML document using XPath. We selected nodes using absolute location paths and relative location paths, and also selected namespace nodes. We discussed the XDK’s XMLDocument class select methods to select elements and attributes in an XML document with XPath. The select methods may be used to select single nodes or collections of nodes. The select methods may also be used to select nodes in a namespace. In the next chapter, you will learn about XSLT(Extensible Stylesheet Language Transformation) support in JDeveloper.

Filed Under: XML Tagged With: XPath

XML Schema Elements – Part2

March 25, 2009 by Krishna Srinivasan Leave a Comment

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

[code lang=”xml”]
<employee grade="senior">
<id>745821</id>
<empName>Tim</empName>
<salary>35000</salary>
<domain>Insurance</domain>
</employee>
[/code]

Define Complex Type in XML schema

Complex types can be defined in XML schema as demonstrated in this example:

[code lang=”xml”]
<xs:element name="employee">
<xs:complexType>
<xs:sequence>
<xs:element name="id" type="xs:string"/>
<xs:element name="empName" type="xs:string"/>
<xs:element name="salary" type="xs:string"/>
<xs:element name="domain" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
[/code]

Define empty elements

Consider the following XML element:

[code lang=”xml”]
<employee empId="157117" />
[/code]

This empty element can be defined in XML schema as follows:

[code lang=”xml”]
<xs:element name="employee">
<xs:complexType>
<xs:attribute name="empId" type="xs:positiveInteger"/>
</xs:complexType>
</xs:element>
[/code]

Here we can see that in the definition we dont define any child elements. We just define the attribute.

Define text only elements

Consider the following XML element:

[code lang=”xml”]
<domain>BFS</domain>
[/code]

The above element can be defined in XML schema as follows:

[code lang=”xml”]
<xs:element name="domain">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:string" />
</xs:simpleContent>
</xs:complexType>
</xs:element>
[/code]

Here, we define that the content of the complex type is simple. In schema terms simple means plain text. The xs:extension is used to declare the type of the data.

Define Mixed Content

Sometimes an XML element can contain elements and text combined. Consider the following example:

[code lang=”xml”]
<employeeInfo>
The employee <id>134567</id>
belongs to <domain>BFS</domain>
and his salary is <salary>56430</salary>
</employeeInfo>
[/code]

The above fragment can be defined in XML schema as follows:

[code lang=”xml”]
<xs:element name="employeeInfo">
<xs:complexType mixed="true">
<xs:sequence>
<xs:element name="id" type="xs:positiveInteger"/>
<xs:element name="domain" type="xs:string"/>
<xs:element name="salary" type="xs:positiveInteger"/>
</xs:sequence>
</xs:complexType>
</xs:element>
[/code]

In the defined XML schema we use the attribute mixed and set its value as true. This indicates that the XML element can contain other elements and simple text as it children

XSD Indicators

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 :

  • Order indicators
  • Occurrence indicators
  • Group indicators

Let us know look at each of these categories.

Order Indicators

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 :

  • All
  • Choice
  • Sequence

All

Using the All 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 :

[code lang=”xml”]
<xs:element name="employee">
<xs:complexType>
<xs:all>
<xs:element name="empId" type="xs:string"/>
<xs:element name="name" type="xs:string"/>
<xs:element name="salary" type="xs:integer"/>
<xs:element name="domain" type="xs:string"/>
</xs:all>
</xs:complexType>
</xs:element>
[/code]

Choice

The Choice indicators specifies that out of all the child elements one can appear. Lets look at an example:

[code lang=”xml”]
<xs:element name="employee">
<xs:complexType>
<xs:choice>
<xs:element name="manager" type="manager"/>
<xs:element name="member" type="member"/>
</xs:choice>
</xs:complexType>
</xs:element>
[/code]

Sequence

This indicator specfies that the child elements should follow the specified order :

[code lang=”xml”]
<xs:element name="employee">
<xs:complexType>
<xs:sequence>
<xs:element name="empId" type="xs:string"/>
<xs:element name="name" type="xs:string"/>
<xs:element name="salary" type="xs:integer"/>
<xs:element name="domain" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
[/code]

Occurrence Indicators

The occurrence indiactor defines the number of times an element can appear. This group has two differetn types:

  • maxOccurs
  • minOccurs

maxOccurs

The maxOccurs element sets an upper limit on the number of times an element can upper. Lets looks at an example:

[code lang=”xml”]
<xs:element name="employee">
<xs:complexType>
<xs:sequence>
<xs:element name="empId" type="xs:string"/>
<xs:element name="name" type="xs:string"/>
<xs:element name="salary" type="xs:integer"/>
<xs:element name="domain" type="xs:string"/>
<xs:element name="project" type="xs:string" maxOccurs="10"/>
</xs:sequence>
</xs:complexType>
</xs:element>
[/code]

minOccurs

The minOccurs element sets the lower imit on the number of times an element can upper. Lets looks at an example:

[code lang=”xml”]
<xs:element name="employee">
<xs:complexType>
<xs:sequence>
<xs:element name="empId" type="xs:string"/>
<xs:element name="name" type="xs:string"/>
<xs:element name="salary" type="xs:integer"/>
<xs:element name="domain" type="xs:string"/>
<xs:element name="project" type="xs:string" maxOccurs="10" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
[/code]

Group Indicators

Group indicators allow us to define a group of elements

  • Group name
  • attributeGroup name

Group Name

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 :

[code lang=”xml”]
<xs:group name="projectGroup">
<xs:sequence>
<xs:element name="projectname" type="xs:string"/>
<xs:element name="technology" type="xs:string"/>
</xs:sequence>
</xs:group>
[/code]

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

[code lang=”xml”]
<xs:element name="employee">
<xs:complexType>
<xs:sequence>
<xs:element name="empId" type="xs:string"/>
<xs:element name="name" type="xs:string"/>
<xs:element name="salary" type="xs:integer"/>
<xs:element name="domain" type="xs:string"/>
<xs:group ref="projectGroup"/>
</xs:sequence>
</xs:complexType>
</xs:element>
[/code]

After making a reference to the projectGroup the employee element gets a total of six child elements:
empId, name, salary, domain, projectname, technology.

Attribute Groups

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 :

[code lang=”xml”]
<xs:attributeGroup name="empAttrGroup">
<xs:attribute name="designation" type="xs:string"/>
</xs:attributeGroup>

<xs:complexType name="employee">
<xs:attributeGroup ref="empAttrGroup"/>
</xs:complexType>

[/code]

The Element
With the use of the any element an XML schema can can extend another XML schema. Lets look at an example :

Filename : employee.xsd
[code lang=”xml”]
<xs:element name="employee">
<xs:complexType>
<xs:sequence>
<xs:element name="empId" type="xs:positiveinteger"/>
<xs:element name="name" type="xs:string"/>
<xs:element name="salary" type="xs:positiveinteger"/>
<xs:element name="domain" type="xs:string"/>
<xs:any minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
[/code]

Filename : children.xsd

[code lang=”xml”]
<xs:element name="project">
<xs:complexType>
<xs:sequence>
<xs:element name="projectName" type="xs:string" />
<xs:element name="technologyUsed" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
[/code]

The XML file can use components from both the files:

[code lang=”xml”]
<employee>
<empId>143233</empId>
<name>John</name>
<salary>34500</salary>
<domain>Insurance</domain>
<project>
<projectName>ISD</projectName>
<technologyUsed>.NET</technologyUsed>
</project>
</employee>
[/code]

XSD Data Types

String
The string data type is used to store characters and strings. For e.g:

[code lang=”xml”]
<table border="1">
<tr>
<td>XML Schema</td>
<td><xs:element name="name" type="xs:string"/></td>
</tr>
<tr>
<td>XML</td>
<td><name>John</name></td>
</tr>
</table>
[/code]

Date

The date type represents a date. The date represented by using the date datatype is specified in the following format : YYYY-MM-DD.
For e.g:

[code lang=”xml”]
<table border="1">
<tr>
<td>XML Schema</td>
<td><xs:element name="joiningDate" type="xs:date"/>
</td>
</tr>
<tr>
<td>XML</td>
<td><joiningDate>2007-03-27</joiningDate></td>
</tr>
</table>
[/code]

Numeric
The numeric data types are of two types:

  • Decimal
  • The decimal data type is used to represent decimal numbers. For e.g:
    [code lang=”xml”]
    <table border="1">
    <tr>
    <td>XML Schema</td>
    <td><xs:element name="price" type="xs:decimal"/></td>
    </tr>
    <tr>
    <td>XML</td>
    <td><price>678.50</price></td>
    </tr>
    </table>
    [/code]

  • Integer
  • The integer data type is used to represent integers. For e.g:
    [code lang=”xml”]
    <table border="1">
    <tr>
    <td>XML Schema</td>
    <td><xs:element name="salary" type="xs:integer"/></td>
    </tr>
    <tr>
    <td>XML</td>
    <td><salary>678.50</salary></td>
    </tr>
    </table>
    [/code]

Other Datatypes

  • Boolean
  • The boolean datatype represents the value true or false.E.g:

    XML Schema
    XML John

[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.]

also read:

  • XML Tutorials
  • How to Parse XML file using DOM Parser?
  • How to Parse XML file using SAX Parser?

Filed Under: XML Tagged With: XML Schema

XML Schema Elements

March 21, 2009 by Krishna Srinivasan Leave a Comment

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.

also read:

  • XML Tutorials
  • How to Parse XML file using DOM Parser?
  • How to Parse XML file using SAX Parser?

Lets create a sample XML schema document empSchema.xsd:
[code lang=”xml”]
<?xml version="1.0" encoding="ISO-8859-1" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="employee">
<xs:complexType>
<xs:sequence>
<xs:element name="id" type="xs:string"/>
<xs:element name="empName" type="xs:string"/>
<xs:element name="salary" type="xs:string"/>
<xs:element name="domain" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
[/code]

Lets create a XML document employee.xml:
[code lang=”xml”]
<?xml version="1.0"?>
<employee
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="empSchema.xsd">
<id>745821</id>
<empName>Tim</empName>
<salary>35000</salary>
<domain>Insurance</domain>
</employee>
[/code]

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.
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.

XML Schema Elements

schema

Every XML schema starts with element as the root. The attribute xmlns:xs=”http://www.w3.org/2001/XMLSchema” says that the elements in the XML document belong to the “http://www.w3.org/2001/XMLSchema” namespace and each of the elements that belong to this namespace should be prefixed with the xs.

Simple Type

A simple type element cannot contain any other elements or attributes. It can contain only text data. For E.g:
[code lang=”xml”]
<table>
<tr>
<td>Syntax:</td>
<td><xs:element name="element-name" type="data-type"/></td>
</tr>
<tr>
<td>XML Schema:</td>
<td><xs:element name="empName" type="xs:string"/></td>
</tr>
<tr>
<td>XML:</td>
<td><empName>Daniel</empName></td>
</tr>
</table>
[/code]
The allowed datatypes in XML schema are :

xs:string
xs:decimal
xs:integer
xs:boolean
xs:date
xs:time

Attributes

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:
[code lang=”xml”]
<table>
<tr>
<td>Syntax:</td>
<td><xs:attribute name="attribute-name" type="data-type"/></td>
</tr>
<tr>
<td>XML Schema:</td>
<td><xs:attribute name="grade" type="xs:string"/></td>
</tr>
<tr>
<td>XML:</td>
<td><employee grade="senior">Daniel</employee></td>
</tr>
</table>
[/code]

Content Restrictions

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 facets.

  • Value restrictions
  • 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.
    In case it happens then the XML document will not validate:
    [code lang=”xml”]
    <xs:element name="salary">
    <xs:simpleType>
    <xs:restriction base="xs:integer">
    <xs:minInclusive value="0"/>
    <xs:maxInclusive value="85000"/>
    </xs:restriction>
    </xs:simpleType>
    </xs:element>
    [/code]

  • Restriction on a set
  • 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:
    [code lang=”xml”]
    <xs:element name="domain">
    <xs:simpleType>
    <xs:restriction base="xs:string">
    <xs:enumeration value="BFS"/>
    <xs:enumeration value="Insurance"/>
    <xs:enumeration value="Manlog"/>
    <xs:enumeration value="Life Sciences"/>
    </xs:restriction>
    </xs:simpleType>
    </xs:element>
    [/code]

  • Restriction on a series
  • 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.
    [code lang=”xml”]
    <xs:element name="number">
    <xs:simpleType>
    <xs:restriction base="xs:string">
    <xs:pattern value="[0-9]"/>
    </xs:restriction>
    </xs:simpleType>
    </xs:element>
    [/code]

  • Restriction on a whitespace characters
  • These restrictions define how the whitespace characters are handled in the XML document. The restriction can be placed using the following syntax:
    [code lang=”xml”]
    <xs:whiteSpace value="preserve"/>
    or
    <xs:whiteSpace value="replace"/>
    [/code]
    The attribute value preserve says that the whitespace characters will not be removed by the XML processor. The attribute value replace says that the following characters will be replaced by spaces :
    line feeds, tabs, spaces, and carriage returns. Lets looks at an example now :
    [code lang=”xml”]
    <xs:element name="feedback"/>
    <xs:simpleType>
    <xs:restriction base="xs:string"/>
    <xs:whiteSpace value="preserve"/>
    </xs:restriction/>
    </xs:simpleType/>
    </xs:element/>
    [/code]

  • Restriction on the length
  • 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
    [code lang=”xml”]
    <xs:element name="empId">
    <xs:simpleType>
    <xs:restriction base="xs:integer">
    <xs:length value="6"/>
    </xs:restriction>
    </xs:simpleType>
    </xs:element>
    [/code]

Filed Under: XML Tagged With: XML Schema

Creating XSLT documents

March 12, 2009 by Krishna Srinivasan Leave a Comment

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 expect the browser to display the document in some meaningful format.
This is where XSLT comes into picture. Using XSLT we can define rules for each XML element in the XML document. Those rules decide how to display the corresponding XML element. XSLT 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. XSLT can be compared with Cascading Style Sheets (CSS). CSS defines the formating rules for HTML tags, XSLT defines the formatting rules for XML tags.

We will be using the following XML document to understand the basic of XSLT :
File Name : employees.xml
[code lang=”xml”]
<?xml version="1.0" encoding="ISO-8859-1"?>
<employees>
<employee vertical="banking">
<id>17452</id>
<name>Jason</name>
<experience>2</experience>
<salary>35000</salary>
</employee>

<employee vertical="insurance">
<id>14782</id>
<name>Jim</name>
<experience>3</experience>
<salary>45000</salary>
</employee>

<employee vertical="telecom">
<id>12563</id>
<name>Charles</name>
<experience>4</experience>
<salary>55000</salary>
</employee>
</employees>
[/code]

Link the XSL Style Sheet to the XML Document

To apply XSLT formatting to the XML document we need to tell the XML document about the XSLT. We can do this by adding the following line to the XML document :

Creating XSLT documents

The root element

As with XML every XSLT document must also start with a root element. The root element should be or .
For E.g :
[code lang=”xml”]
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
or
<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
[/code]
By adding the XSLT namespace attribute, xmlns:xsl, access is provided to elements, attributes.
The value of xmlns:xsl points to the official W3C XSLT namespace. We must also include the atribute version.

Defining templates

In XSLT 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 XSLT templates can be defined using xsl:template element.

xsl:template element has a match attribute which associates a template with an XML element.
With the match element we can also associate a template with the entire document.

For E.g :
[code lang=”xml”]
<?xml version="1.0" encoding="ISO-8859-1"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<table border="1">
<tr bgcolor="#9acd32">
<th>Id</th>
<th>Name</th>
</tr>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
[/code]
Output:

Id Name

Explanation:
This is just a trivial example where we dont do much expect creating two headers. In the example above the xsl:template element associates the template to the root element. This is achieved by using match=”/”. This essesntially says if the xml root element is encountered then apply this template. Inside the template we define some HTML to display.

Extracting values of XML elements

We can extract the values of XML elements using the xsl:value-of element.
For E.g:
[code lang=”xml”]
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<table border="1">
<tr bgcolor="#9acd32">
<th>Id</th>
<th>Name</th>
</tr>
<tr>
<td><xsl:value-of select="employees/employee/id"/></td>
<td><xsl:value-of select="employees/employee/name"/></td>
</tr>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
[/code]

Output:

Id Name
17452 Jason

Explanation:
This example does nothing much than just displaying the values of the first id and the name element encountered in the xml document. It skips the rest of id and the name elements. We can print all the missing elements using which we will see in the next section.

Select every XML element

The element allows us to perform iterations in the XML document.
For E.g :
[code lang=”xml”]
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<table border="1">
<tr bgcolor="#9acd32">
<th>Id</th>
<th>Name</th>
</tr>
<xsl:for-each select="employees/employee">
<tr>
<td><xsl:value-of select="id"/></td>
<td><xsl:value-of select="name"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
[/code]
Output:

Id Name
17452 Jason
14782 Jim
12563 Charles

Explanation:
In the example we can see that each of the element is iterated over and the values of the corresponding id and name elements are printed

Filtering the content

We can filter the result generated by XSLT. Using filtering we can display certain content and not display others.
For E.g :

Sorting the output

We can sort the output generated by XSLT by using the element.
For E.g:
[code lang=”xml”]
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<table border="1">
<tr bgcolor="#9acd32">
<th>Id</th>
<th>Name</th>
</tr>
<xsl:for-each select="employees/employee">
<xsl:sort select="name"/>
<tr>
<td><xsl:value-of select="id"/></td>
<td><xsl:value-of select="name"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
[/code]
Output:

Id Name
12563 Charles
17452 Jason
14782 Jim

Conditional test

To test for certain condition on the content generated by XSLT we can use element.
For E.g :
[code lang=”xml”]
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<table border="1">
<tr bgcolor="#9acd32">
<th>Id</th>
<th>Name</th>
</tr>
<xsl:for-each select="employees/employee">
<xsl:if test="salary > 45000">
<tr>
<td><xsl:value-of select="id"/></td>
<td><xsl:value-of select="name"/></td>
</tr>
</xsl:if>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
[/code]

Output:

Id Name
12563 Charles

Multiple conditional tests

XSLT 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

Consider the following E.g:
[code lang=”xml”]
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<table border="1">
<tr bgcolor="#9acd32">
<th>Id</th>
<th>Name</th>
</tr>

<xsl:for-each select="employees/employee">
<xsl:choose>
<xsl:when test="salary > 45000">
<tr bgcolor="#F00E0E">
<td><xsl:value-of select="id"/></td>
<td><xsl:value-of select="name"/></td>
</tr>
</xsl:when>
<xsl:otherwise>
<tr bgcolor="#235CDB">
<td><xsl:value-of select="id"/></td>
<td><xsl:value-of select="name"/></td>
</tr>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
[/code]

Output:

Id Name
17452 Jason
14782 Jim
12563 Charles

Explanation:
The example above explains the usage of element. Here we display employee rows in different colors based on a salary range

Apply Templates

We can apply a template to either of these :
– The root
– The current element
– The children of the current element

We can apply templates by using the element. The takes an attribute called select. 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 :

[code lang=”xml”]
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>

<xsl:template match="employee">

<xsl:apply-templates select="name"/>
<xsl:apply-templates select="salary"/>

</xsl:template><xsl:template match="name">
Name: <span style="color:#ff0000">
<xsl:value-of select="."/></span>

<br />

</xsl:template><xsl:template match="salary">
Salary: <span style="color:#00ff00">
<xsl:value-of select="."/></span>
<br />

</xsl:template>
</xsl:stylesheet>

[/code]

Output:
Name:Jason
Salary:35000

Name:Jason
Salary:35000

Name:Jason
Salary:35000

Explanation:
The xsl:apply-templates in between the body tags declares that the template should be applied to the entire document.
When an employee element is encountered the matched template is executed. However, inside the employee template we instruct the XSLT processor to apply template to matching name element and salary element. In the matched template we define the rules to display the current element.

[Note: select=”.” refers to the current node]

also read:

  • XML Tutorials
  • How to Parse XML file using DOM Parser?
  • How to Parse XML file using SAX Parser?

Filed Under: XML Tagged With: XSLT

  • 1
  • 2
  • Next Page »

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved