PK
G@Aoa, mimetypeapplication/epub+zipPK G@A iTunesMetadata.plistW
This chapter contains these topics:
The Java XDK components are included with Oracle Database. This chapter assumes that you have installed XDK with Oracle Database and also installed the demo programs on the Oracle Database Examples media. Refer to "Installing the XDK" for installation instructions and a description of the XDK directory structure.
Example 3-1 shows the UNIX directory structure for the XDK demos and the libraries used by the XDK components. The $ORACLE_HOME/xdk/demo/java
subdirectories contain sample programs and data files for the XDK for Java components. The chapters in Part I, "XDK for Java" explain how to understand and use these programs.
Example 3-1 Java XDK Libraries, Utilities, and Demos
- Oracle_home_directory | - bin/ orajaxb orapipe oraxml oraxsl transx | - lib/ classgen.jar jdev-rt.zip oraclexsql.jar transx.zip xml.jar xml2.jar xmlcomp.jar xmlcomp2.jar xmldemo.jar xmlmesg.jar xmlparserv2.jar xschema.jar xsqlserializers.jar xsu12.jar | - jlib/ orai18n.jar orai18n-collation.jar orai18n-mapping.jar orai18n-utility.jar | - jdbc/ | - lib/ ojdbc5.jar | - rdbms/ | - jlib/ xdb.jar
| - xdk/ | demo/ | - java/ | - classgen/ | - jaxb/ | - parser/ | - pipeline/ | - schema/ | - transviewer/ | - tranxs/ | - xsql/ | - xsu/
The subdirectories contain sample programs and data files for the Java XDK components. The chapters in Part I, "XDK for Java" explain how to use these programs to gain an understanding of the most important Java features.
The Java XDK components are certified and supported with JDK version 5 and version 6. Earlier versions of Java are no longer supported. Figure 3-1 shows the dependencies of Java XDK components when using JDK 5.
Figure 3-1 Java XDK Component Dependencies for JDK 5
The Java XDK components require the libraries alphabetically listed in Table 3-1. Note that some of the libraries are not specific to the XDK, but are shared among other Oracle Database components.
Table 3-1 Java Libraries for XDK Components
Library | Directory | Includes . . . |
---|---|---|
|
|
XML class generator for Java runtime classes. Note: This library is maintained for backward compatibility only. You should use the JAXB class generator in |
|
|
Java GUI libraries for use when working with the demos with the JDeveloper IDE. |
|
|
Oracle JDBC drivers for Java 5, 6. This JAR depends on |
|
|
Most of the XSQL Servlet classes needed to construct XSQL pages. Note: This archive is superseded by |
|
|
Globalization support for JDK 1.2 or above. It is a wrapper of all other Globalization jars and includes character set converters. If you use a multibyte character set other than UTF-8, ISO8859-1, or JA16SJIS, then place this archive in your |
|
|
Globalization collation features: the |
|
|
Globalization locale and character set name mappings: the |
|
|
Globalization locale objects: the |
|
|
TransX Utility classes. Note: This archive is replaced by |
|
|
Classes needed by |
|
|
Classes from the following libraries:
The archive also contains the JAXB and Pipeline Processor classes. |
|
|
XML JavaBeans that do not depend on the database: Note: This archive is included for backward compatibility only because its classes are included in |
|
|
XML JavaBeans that depend on the database: Note: This JAR is included for backward compatibility only because its classes are included in |
|
|
The visual JavaBeans: |
|
|
Needed if you use XML parser with a language other than English. |
|
|
APIs for the following:
This library includes |
|
|
Includes the XML Schema classes contained in Note: This JAR file is maintained for backward compatibility only. |
|
|
Serializer classes for XSQL Servlet needed for serialized output such as PDF. Note: This archive is superseded by |
|
|
Classes that implement XSU. These classes have a dependency on |
See Also:
|
In the Oracle Database installation of the XDK, you must manually set the $CLASSPATH
(UNIX) or %CLASSPATH%
(Windows) environment variables. Alternatively, set the -classpath
option when compiling and running Java programs at the command line.
This section contains the following topics:
Table 3-2 describes the UNIX environment variables required for use with the Java XDK components.
Table 3-2 UNIX Environment Settings for Java XDK Components
Variable | Description |
---|---|
|
Includes the following (note that a single period "." to represent the current directory is not required but may be useful):
|
|
For JDK 5, set as follows:
The |
|
Installation directory for the Java JDK, Standard Edition. Modify the path that links to the Java SDK. |
|
For OCI JDBC connections:
|
|
|
Table 3-3 describes the command-line utilities included in the Java XDK on UNIX. Before you can use these utilities, you must set up your environment.
Table 3-3 Java XDK Utilities
Executable/Class | Directory/JAR | Description |
---|---|---|
|
|
XSQL command-line utility. The script executes the |
|
|
XSU command-line utility See Also: "Using the XSU Command-Line Utility" |
|
|
JAXB command-line utility See Also: "Using the JAXB Class Generator Command-Line Utility" |
|
|
Pipeline command-line utility See Also: "Using the XML Pipeline Processor Command-Line Utility" |
|
|
XML parser command-line utility |
|
|
XSLT processor command-line utility |
|
|
TransX command-line utility See Also: "Using the TransX Command-Line Utility" |
If your environment is set up correctly, then the UNIX shell script shown in Example 3-2 should generate version and usage information for the utilities.
Example 3-2 Testing the Java XDK Environment on UNIX
#!/usr/bin/tcsh echo;echo "BEGIN TESTING";echo echo;echo "now testing the XSQL utility...";echo xsql echo; echo "now testing the XSU utility...";echo java OracleXML echo;echo "now testing the JAXB utility...";echo orajaxb -version echo;echo "now testing the Pipeline utility...";echo orapipe -version echo;echo "now testing the XSLT Processor utility...";echo oraxsl echo;echo "now testing the TransX utility...";echo transx echo;echo "END TESTING"
Table 3-4 describes the Windows environment variables required for use with the Java XDK components.
Table 3-4 Windows Environment Settings for Java XDK Components
Variable | Notes |
---|---|
|
Includes the following (note that a single period "." to represent the current directory is not required but may be useful):
|
|
For JDK 5, set as follows:
The |
|
Installation directory for the Java SDK, Standard Edition. Modify the path that links to the Java SDK. |
|
|
Table 3-5 describes the command-line utilities included in the Java XDK on Windows. Before you can use these utilities, you must set up your environment.
Table 3-5 Java XDK Utilities
Batch File/Class | Directory/JAR | Description |
---|---|---|
|
|
XSQL command-line utility. The batch file executes the |
|
|
XSU command-line utility See Also: "Using the XSU Command-Line Utility" |
|
|
JAXB command-line utility See Also: "Using the JAXB Class Generator Command-Line Utility" |
|
|
Pipeline command-line utility See Also: "Using the XML Pipeline Processor Command-Line Utility" |
|
|
XML parser command-line utility |
|
|
XSLT processor command-line utility |
|
|
TransX command-line utility See Also: "Using the TransX Command-Line Utility" |
If your environment is set up correctly, then you can run the commands in Example 3-3 at the system prompt to generate version and usage information for the utilities.
To obtain the version of XDK you are working with, use javac
to compile the Java code shown in Example 3-4.
Example 3-4 XDKVersion.java
// // XDKVersion.java // import java.net.URL; import oracle.xml.parser.v2.XMLParser; public class XDKVersion { static public void main(String[] argv) { System.out.println("You are using version: "); System.out.println(XMLParser.getReleaseVersion()); } }
After compiling the source file with javac
, run the program on the operating system command line as follows:
java XDKVersion You are using version: Oracle XML Developers Kit 11.1.0.6.0 - Production
The Oracle XDK includes components that help you to determine the differences between the contents of two XML documents and then to apply the differences (patch) to one of the XML documents.
This chapter contains these topics:
You can use Oracle XmlDiff
to determine the differences between two similar XML documents. XmlDiff
generates an Xdiff
instance document that indicates the differences. The Xdiff
instance document is an XML document that conforms to an XML schema, the Xdiff
schema.
You can then use XmlPatch
, which takes the Xdiff
instance document and applies the changes to other documents. This can be used to apply the same changes to a large number of XML documents.
XmlDiff
only supports the DOM API for input and output.
XmlPatch
also supports the DOM for the input and patch documents.
XmlDiff
and XmlPatch
can be used through a C API or a command line tool, and they are exposed by two SQL functions.
An XmlHash
C API is provided to compute the hash value of an XML tree or subtree. If hash values of two trees or subtrees are equal, the trees are identical to a very high probability.
The flow of the process is as follows:
The two input documents are compared by XmlDiff
.
XmlDiff
creates a Xdiff
instance document.
The application can pass the Xdiff
instance document to XmlPatch
, if this is required.
XmlPatch
can apply the differences captured from the comparison to other documents as specified by the application.
XmlDiff
compares the trees that represent the two input documents to determine differences.
Both input documents must use the same character-set encoding. The Xdiff
(output) instance document has the same encoding as the data encoding (DOM encoding) of the input documents.
There are two options for the comparison, known as optimizations:
Global Optimization - Default
The whole document trees are compared.
Local Optimization
Comparison is at the sibling level. Local optimization compares siblings under the corresponding parents from two trees.
Global optimization can take more time and space for large documents but always produces the smallest set of differences (the optimal difference). Local optimization is much faster, but may not produce the optimal difference.
Hashing generally speeds up global optimization with a small possible loss in quality. Hashing improves the quality of the difference output, with local optimization. Using different hash levels may generate both local and global differences.
You can specify the use of hashing for both local and global optimization.
To specify hashing, provide the hashLevel
parameter. If hashLevel
is greater than 1, then only the DOMHash
values are used for comparing all subtrees at depth >= hashLevel
of difference. If the hash values are equal, then the subtrees are presumed to be equal.
XmlDiff
ignores differences in the order of attributes while doing the comparison.
XmlDiff
ignores DocType declarations. Files are not validated against the DTD.
XmlDiff
ignores any differences in the namespace prefixes as long as the namespace prefixes refer to the same namespace URI. Otherwise, if two nodes have the same local name and content but differ in namespace URI, these differences are indicated.
Note: XmlDiff operates on its input documents in a nonschema-based way. It does not operate on elements or attributes in a type-aware manner. |
Table 21-1 describes command line options:
Table 21-1 XmlDiff for Command Line Options for the C Language
Option | Description |
---|---|
|
Specify default input-file encoding. If no encoding is specified in XML file, this encoding is assumed for input. |
|
Specify output/data encoding. DOMs and the |
|
Specify the hash level. If greater than |
|
Set global optimization (default). |
|
Set local optimization. |
|
Show this usage help. |
|
Disable update operation. |
Example 21-1 is a sample xml
document that can be used to explain updates resulting from using both XmlDiff
and XmlPatch
. It is followed by some hypothetical changes.
Example 21-1 book1.xml
<?xml version="1.0"?> <booklist xmlns="http://booklist.oracle.com"> <book> <title>Twelve Red Herrings</title> <author>Jeffrey Archer</author> <publisher>Harper Collins</publisher> <price>7.99</price> </book> <book> <title language="English">The Eleventh Commandment</title> <author>Jeffrey Archer</author> <publisher>McGraw Hill</publisher> <price>3.99</price> </book> <book> <title language="English" country="USA">C++ Primer</title> <author>Lippmann</author> <publisher>Harper Collins</publisher> <price>4.99</price> </book> <book> <title>Emperor's New Mind</title> <author>Roger Penrose</author> <publisher>Oxford Publishing Company</publisher> <price>15.9</price> </book> <book> <title>Evening News</title> <author>Arthur Hailey</author> <publisher>MacMillan Publishers</publisher> <price>9.99</price> </book> </booklist>
Assume that there is another file, book2.xml
, that looks just like the Example 21-1, "book1.xml" except that it results in the following:
Deletes "The Eleventh Commandment", a delete-node
operation.
Changes the country code for the "C++ Primer" to US from USA, an update-node
operation.
Adds a description to "Emperor's New Mind", an append-node
operation.
Add the edition to "Evening News", an insert-node-before
operation.
Updates the price of "Evening News", an update-node
operation.
This section shows the Xdiff
instance document produced by the comparison of these two XML files described in the previous section. The sections that follow explain the XML processing instructions and the operations on this document.
You can invoke XmlDiff
as follows:
> xmldiff book1.xml book2.xml
You can also examine the sample application for arguments and flags.
Example 21-2 Sample Xdiff Instance Document
<?xml version="1.0" encoding="UTF-8"?> <xd:xdiff xsi:schemaLocation="http://xmlns.oracle.com/xdb/xdiff.xsd xmlns:xd="http://xmlns.oracle.com/xdb/xdiff.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oraxdfns_0="http://booklist.oracle.com"> <?oracle-xmldiff operations-in-docorder="true" output-model="snapshot" diff-algorithm="global"?> <xd:delete-node xd:node-type="element" xd:xpath="/oraxdfns_0 :booklist[1]/oraxdfns_0:book[2]"/> <xd:update-node xd:node-type="attribute" xd:parent-xpath="/oraxdfns_0:booklist[1]/oraxdfns_0:book[3]/oraxdfns_0 :title[1]" xd:attr-local="country"> <xd:content>US</xd:content> </xd:update-node> <xd:append-node xd:node-type="element" xd:parent-xpath="/oraxdfns_0 :booklist[1]/oraxdfns_0:book[4]"> <xd:content> <oraxdfns_0:description> This is a classic </oraxdfns_0:description> </xd:content> </xd:append-node> <xd:insert-node-before xd:node-type="element" xd:xpath="/oraxdfns_0 :booklist[1]/oraxdfns_0:book[5]/oraxdfns_0:author[1]"> <xd:content> <oraxdfns_0:edition>Hardcover</oraxdfns_0:edition> </xd:content> </xd:insert-node-before> <xd:update-node xd:node-type="text" xd:xpath="/oraxdfns_0 :booklist[1]/oraxdfns_0:book[5]/oraxdfns_0:price[1]/text()[1]"> <xd:content>12.99</xd:content> </xd:update-node> </xd:xdiff>
The Xdiff
instance document uses some XML processing instructions (shown in bold in the previous section) that are used to represent certain aspects of the differencing process. See "Xdiff Schema". These instructions and related options are:
operations-in-docorder
: Options are true
or false
:
true
- The Xdiff
instance document refers to the nodes from the first document in the same order as in the document.
false
- The Xdiff
instance document does not refer to the nodes from the first document in the same order as in the document.
The output of global optimization meets the operations-in-docorder
requirement, but local optimization does not.
output-model
: Options are:
snapshot
- Xmldiff generates output in snapshot model and follows the UNIX diff model. Each operation uses XPath
as if no operations have been applied to the input document. This is the default. XmlPatch
can only handle this model if operations-in-docorder
is set to true
and the XPath
s are simple. Simple XPath
s require a child axis, no wild cards, and must use positional predicates, such as /root[1]/child[2]/text()[2]
.
current
- Each operation uses XPath
as if all operations up to the previous one have been applied to the input document. Even though XmlDiff
does not generate differences in the current model, XmlPatch
can handle a hand-crafted diff
document in the current model
diff-algorithm
: Options indicate which optimization generated the differences.
Global optimization
Local optimization
XmlDiff
captures differences using operations indicated by the Xdiff
instance document.
Note the following about Xdiff
operations:
The parent-xpath
attribute or xpath
attribute specifies the XPATH
location of the parent node of the node to be operated on or XPATH
location of node.
The node-type
attribute specifies the type of the node to be operated on.
The content
child element specifies the new subtree or value appended or inserted.
The Xdiff
operations, presented in the Xdiff Instance Document, are as follows:
append-node
:
The append-node
element specifies that a node of the given type is added as the last child of the given parent.
insert-node-before
:
The insert-node-before
element specifies that a node of the given type is inserted before the given reference node.
delete-node
:
The delete-node
element specifies that the node be deleted along with all its children. This can be used to delete elements, comments, and so on.
update-node
:
update-node
specifies that the value associated with the node with the given XPath
expression is updated to the new value, which is specified. Content is the value for a text node. The value of an attribute is the value for an attribute node.
Update for Text Nodes:
Generation of update node operations can be turned off by the user.
The value of an attribute is the value for an attribute node.
update-node
is generated for text nodes only by global optimization.
Update for Elements:
XmlDiff
does not generate update operations for element nodes.
You can either manually modify the Xdiff
instance document to create an update operation that works with XmlPatch
, or provide a totally hand-written Xdiff
instance document. All children of the element operated on by the update are deleted. Any new subtree specified under the content node is imported.
The output of XmlDiff
, the Xdiff
instance document, is in XML format and conforms to the Xdiff
schema shown in the next section.
The output document contains a sequence of operations describing the differences between the two input documents. If you apply the differences from the first document, you get the second document.
Example 21-3 shows the Xdiff
schema to which the Xdiff
instance document (output) adheres.
Example 21-3 Xdiff Schema: xdiff.xsd
<schema targetNamespace="http://xmlns.oracle.com/xdb/xdiff.xsd" xmlns="http://www.w3.org/2001/XMLSchema" xmlns:xd="http://xmlns.oracle.com/xdb/xdiff.xsd" version="1.0" elementFormDefault="qualified" attributeFormDefault="qualified"> <annotation> <documentation xml:lang="en"> Defines the structure of XML documents that capture the difference between two XML documents. Changes that are not supported by Oracle XmlDiff may not be expressible in this schema. 'oracle-xmldiff' PI in Xdiff document: We use 'oracle-xmldiff' PI to describe certain aspects of the diff. The PI denotes values for 'operations-in-docorder' and 'output-model'. The output of XmlDiff has the PI always. If the user hand-codes a diff doc then it must also have the PI in it as the first child of top level xdiff element, to be able to call XmlPatch. operations-in-docorder: Can be either 'true' or 'false'. If true, the operations in the diff document refer to the elements of the input doc in the same order as document order. Output of global algorithm meets this requirement while local does not. output-model: output models for representing the diff. Can be either 'Snapshot' or 'Current'. Snapshot model: Each operation uses Xpaths as if no operations have been applied to the input document. (like UNIX diff) This is the model used in the output of XmlDiff. XmlPatch works with this (and the current model too). For XmlPatch to handle this model, "operations-in-docorder" must be true and the Xpaths must be simple. (see XmlDif C API documentation). Current model: Each operation uses Xpaths as if all operations till the previous one have been applied to the input document. Works with XmlPatch even if the 'operations-in-docorder' criterion is not met and the xpaths are not simple. <!-- Example: <?oracle-xmldiff operations-in-docorder="true" output-model= "snapshot" diff-algorithm="global"?> --> </documentation> </annotation> <!-- Enumerate the supported node types --> <simpleType name="xdiff-nodetype"> <restriction base="string"> <enumeration value="element"/> <enumeration value="attribute"/> <enumeration value="text"/> <enumeration value="cdata"/> <enumeration value="entity-reference"/> <enumeration value="entity"/> <enumeration value="processing-instruction"/> <enumeration value="notation"/> <enumeration value="comment"/> </restriction> </simpleType> <element name="xdiff"> <complexType> <choice minOccurs="0" maxOccurs="unbounded"> <element name="append-node"> <complexType> <sequence> <element name="content" type="anyType"/> </sequence> <attribute name="node-type" type="xd:xdiff-nodetype"/> <attribute name="xpath" type="string"/> <attribute name="parent-xpath" type="string"/> <attribute name="attr-local" type="string"/> <attribute name="attr-nsuri" type="string"/> </complexType> </element> <element name="insert-node-before"> <complexType> <sequence> <element name="content" type="anyType"/> </sequence> <attribute name="xpath" type="string"/> <attribute name="node-type" type="xd:xdiff-nodetype"/> </complexType> </element> <element name="delete-node"> <complexType> <attribute name="node-type" type="xd:xdiff-nodetype"/> <attribute name="xpath" type="string"/> <attribute name="parent-xpath" type="string"/> <attribute name="attr-local" type="string"/> <attribute name="attr-nsuri" type="string"/> </complexType> </element> <element name="update-node"> <complexType> <sequence> <element name="content" type="anyType"/> </sequence> <attribute name="node-type" type="xd:xdiff-nodetype"/> <attribute name="parent-xpath" type="string"/> <attribute name="xpath" type="string"/> <attribute name="attr-local" type="string"/> <attribute name="attr-nsuri" type="string"/> </complexType> </element> <element name="rename-node"> <complexType> <sequence> <element name="content" type="anyType"/> </sequence> <attribute name="xpath" type="string"/> <attribute name="node-type" type="xd:xdiff-nodetype"/> </complexType> </element> </choice> <attribute name="xdiff-version" type="string"/> </complexType> </element> </schema>
In an application, XmlDiff
takes the source types and locations of the input documents as arguments. The source type can be a URL, file, orastream
and stream
context pointers, buffer, and buffer_length
pointers or the pointer to a DOM document element (docelement
).
XmlDiff
returns the document node for the DOM for the Xdiff
instance document.
XmlDiff builds the DOM for the two documents, if they are not already provided as DOM, before performing a comparison.
See Also: Oracle Database XML C API Reference, for the C API for the flags that control the behavior ofXmlDiff |
Example 21-4 XMLDiff Application
# include <xmldf.h> ... xmlctx *xctx; xmldocnode *doc1, *doc2, *doc3; uword hash_level; oratext *s, *inp1 = "book1.xml", *inp2="book2.xml"; xmlerr err; ub4 flags; flags = 0; /* defaults : global algorithm */ hash_level = 0; /* no hashing */ /* create XML meta context */ if (!(xctx = XmlCreate(&err, (oratext *) "XmlDiff", NULL))) { printf("Failed to create XML context, error %u\n", (unsigned) err); err_exit("Exiting"); } /* Load the two input files */ if (!(doc1 = XmlLoadDom(xctx, &err, "file", inp1, "discard_whitespace", TRUE, NULL))) { printf("Parsing first file failed, error %u\n", (unsigned)err); err_exit((oratext *)"Exiting."); } if (!(doc2 = XmlLoadDom(xctx, &err, "file", inp2, "discard_whitespace", TRUE, NULL))) { printf("Parsing second file failed, error %u\n", (unsigned)err); err_exit((oratext *)"Exiting."); } /* run XmlDiff on the DOM trees. */ doc3 = XmlDiff(xctx, &err, flags, XMLDF_SRCT_DOM, doc1, NULL, XMLDF_SRCT_DOM, doc2, NULL,hash_level, NULL); if(!doc3) printf("XmlDiff Failed, error %u\n", (unsigned)err); else { if(err != XMLERR_OK) printf("XmlDiff returned error %u\n", (unsigned)err); /* Now we have the DOM tree in doc3 which represent the Diff */ ... } XmlFreeDocument(xctx, doc1); XmlFreeDocument(xctx, doc2); XmlFreeDocument(xctx, doc3); XmlDestroy(xctx);
A customized output builder stores differences in any format suitable to the application. You can create your own customized output builder, rather than using the default Xdiff
instance document, generated by XmlDiff
and which conforms to the Xdiff
schema.
To do this, you must provide a callback that can be called after XmlDiff
determines the differences. The differences are passed to the callback as an array of xmdlfop
. The callback may be called multiple times as the differences are being generated.
Using a customized output builder may perform better than using the default, because it does not have to maintain the internal state necessary for XPath
generation.
By default, XmlDiff
captures the differences in XML conforming to Xdiff
schema. If necessary, plug in your own output builder. The differences are represented as an array xmldfop
. You must write an output builder callback function. The function signature is:
xmlerr(*xdfobcb)(void *uctx, xmldfop *escript, ub4 escript_siz);
uctx
is the user specific context.
escript
is the array of size escript_siz
:
diff[escript_siz]
mctx
is the memory context.
Supply this memory context through properties to XmlDiff()
. Use this memory context to allocate escript
. You must later free escript
.
Invoke the output builder callback after the differences have been found which happens even before the call to XmlDiff()
returns. The output builder callback can be called multiple times.
Example 21-5 Customized XMLDiff Output
/* Sample useage: */ ... #include <orastruc.h> / * for 'oraprop' * / ... static oraprop diff_props[] = { ORAPROP(XMLDF_PROPN_CUSTOM_OB, X%MLDF_PROPI_CUSTOM_OB, POINTER), ORAPROP(XMLDF_PROPN_CUSTOM_OBMCX, XMLDF_PROPI_CUSTOM_OBMCX, POINTER), ORAPROP(XMLDF_PROPN_CUSTOM_OBUCX, XMLDF_PROPI_CUSTOM_OBUCX, POINTER), { NULL } }; ... oramemctx *mymemctx; ... xmlerr myob(void *uctx, xmldfop *escript, ub4 escript_siz) { /* process diff which is available in escript * / /* free escript - the caller has to do this * / OraMemFree(mymemctx, escript); } main() { ... myctxt *myctx; diff_props[0].value_oraprop.p_oraprop_v = myob; diff_props[1].value_oraprop.p_oraprop_v = mymemctx; diff_props[2].value_oraprop.p_oraprop_v = myctx; XmlDiff(xctx, &err, 0, doc1, NULL, 0, doc2, NULL, 0, diff_props); ... }
XmlPatch
takes the Xdiff
instance document, either as generated by XmlDiff
or created by another mechanism, and follows the instructions in the Xdiff
instance document to modify other XML documents as specified.
Table 21-2 describes the XmlPatch
command line options:
Table 21-2 XmlPatch for C Command Line Options
Option | Description |
---|---|
|
Specify default input-file encoding. If no encoding is specified in XML file, this encoding is assumed for input. |
|
Specify output/data encoding. DOMs and patched document are created in this encoding. Default is UTF8. |
|
Interpret file names as URLs. |
|
Show this usage help. |
XmlPatch
takes the source types and locations of the input document and the diff
document as arguments. The source type can be a URL, file, orastream
and stream
context pointers, buffer and buffer_length
pointers, or the pointer to a DOM document element (docelement
).
See Also: Oracle Database XML C API Reference, for the C API for the flags that control the behavior ofXmlPatch |
The modes that were set by the Xdiff
schema affect how XmlPatch
works.
If the output-model
is Snapshot
, XmlPatch
only works if operations-in-docorder
is TRUE
.
If the output-model
is Current
, it is not necessary that operations-in-docorder
be set to TRUE
.
Example 21-6 Sample Application for XmlPatch
... #include <xmldf.h> ... xmlctx *xctx; xmldocnode *doc1, *doc2; oratext *s; oratext *inp1 = "book1.xml"; /* input document */ oratext *inp2 = "diff.xml", /* diff document */ xmlerr err; /* create XML meta context */ if (!(xctx = XmlCreate(&err, (oratext *) "XmlPatch", NULL))) { printf("Failed to create XML context, error %u\n", (unsigned) err); err_exit("Exiting"); } /* Load the two input files */ if (!(doc1 = XmlLoadDom(xctx, &err, "file", inp1, "discard_whitespace", TRUE, NULL))) { printf("Parsing first file failed, error %u\n", (unsigned)err); err_exit((oratext *)"Exiting."); } if (!(doc2 = XmlLoadDom(xctx, &err, "file", inp2, "discard_whitespace", TRUE, NULL))) { printf("Parsing second file failed, error %u\n", (unsigned)err); err_exit((oratext *)"Exiting."); } /* call XmlPatch */ if(!XmlPatch(xctx, &err, 0, XMLDF_SRCT_DOM, doc1, NULL, XMLDF_SRCT_DOM, doc2, NULL, NULL)); printf("XmlPatch Failed, error %u\n", (unsigned)err); else { if(err != XMLERR_OK) printf("XmlPatch returned error %u\n", (unsigned)err); /* Now we have the patched document in doc1 */ ... } XmlFreeDocument(xctx, doc1); XmlFreeDocument(xctx, doc2); XmlDestroy(xctx);
Oracle XDK provides XmlHash,
which computes a hash value for an XML tree or subtree. If the hash values of two subtrees are equal, it is highly probable that they are the same XML. This can be used to do a quick comparison, for example, if you want to see if the XML tree is already in the database.
You can run XmlDiff
again, if necessary, on any matches, to be absolutely certain there is a match. You can compute the hash value of the new document and query the database for it.
Example 21-7 shows a sample program that uses XmlHash
.
Example 21-7 XmlHash Program
sword main(sword argc, char *argv[]) { xmlctx *xctx; xmldfsrct srct; oratext *data_encoding, *input_encoding, *s, *inp1; ub1 flags; xmlerr err; ub4 num_args; xmlhasht digest; flags = 0; /* defaults */ srct = XMLDF_SRCT_FILE; inp1 = "somexml.xml"; xctx = XmlCreate(&err, (oratext *) "XmlHash", NULL); if (!xctx) { /* handle error with creating xml context and exit */ ... } /* run XmlHash */ err = XmlHash(xctx, &digest, 0, srct, inp1, NULL, NULL); if(err) printf("XmlHash returned error:%d \n", err); else txdfha_pd(digest); XmlDestroy(xctx); return (sword )err; } /* print bytes in xml hash */ static void txdfha_pd(xmlhasht digest) { ub4 i; for(i = 0; i < digest.l_xmlhasht; i++) printf("%x ", digest.d_xmlhasht[i]); printf("\n"); }
This chapter contains these topics:
This section contains the following topics:
This chapter assumes that you are familiar with the following topics:
XML Pipeline Definition Language. This XML vocabulary enables you to describe the processing relations between XML resources. If you require a more thorough introduction to the Pipeline Definition Language, consult the XML resources listed in "Related Documents" of the preface.
Document Object Model (DOM). DOM is an in-memory tree representation of the structure of an XML document.
Simple API for XML (SAX). SAX is a standard for event-based XML parsing.
XML Schema language. Refer to Chapter 7, "Using the Schema Processor for Java" for an overview and links to suggested reading.
The Oracle XML Pipeline processor is based on the W3C XML Pipeline Definition Language Version 1.0 Note. The W3C Note defines an XML vocabulary rather than an API. You can find the Pipeline specification at the following URL:
http://www.w3.org/TR/xml-pipeline/
"Pipeline Definition Language Standard for the XDK for Java" describes the differences between the Oracle XDK implementation of the Oracle XML Pipeline processor and the W3C Note.
The Oracle XML Pipeline processor is built on the XML Pipeline Definition Language. The processor can take an input XML pipeline document and execute pipeline processes according to derived dependencies. A pipeline document, which is written in XML, specifies the processes to be executed in a declarative manner. You can associate Java classes with processes by using the <processdef/>
element in the pipeline document.
Use the Pipeline processor for mutistage processing, which occurs when you process XML components sequentially or in parallel. The output of one stage of processing can become the input of another stage of processing. You can write a pipeline document that defines the inputs and outputs of the processes. Figure 9-1 illustrates a possible pipeline sequence.
In addition to the XML Pipeline processor itself, the XDK provides an API for processes that you can pipe together in a pipeline document. Table 9-2 summarizes the classes provided in the oracle.xml.pipeline.processes
package.
The typical stages of processing XML in a pipeline are as follows:
Parse the input XML documents. The oracle.xml.pipeline.processes
package includes DOMParserProcess
for DOM parsing and SAXParserProcess
for SAX parsing.
Validate the input XML documents.
Serialize or transform the input documents. Note that the Pipeline processor does not enable you to connect the SAX parser to the XSLT processor, which requires a DOM.
In multistage processing, SAX is ideal for filtering and searching large XML documents. You should use DOM when you need to change XML content or require efficient dynamic access to the content.
See Also: "Processing XML in a Pipeline" to learn how to write a pipeline document that provides the input for a pipeline application |
The oracle.xml.pipeline.controller.Process
class is the base class for all pipeline process definitions. The classes in the oracle.xml.pipeline.processes
package extend this base class. To create a customized pipeline process, you need to create a class that extends the Process
class.
At the minimum, every custom process should override the do-nothing initialize()
and execute()
methods of the Process
class. If the customized process accepts SAX events as input, then it should override the SAXContentHandler()
method to return the appropriate ContentHandler
that handles incoming SAX events. It should also override the SAXErrorHandler()
method to return the appropriate ErrorHandler
. Table 9-1 provides further descriptions of the preceding methods.
Table 9-1 Methods in the oracle.xml.pipeline.controller.Process Class
Class | Description |
---|---|
|
Initializes the process before execution. Call |
|
Executes the process. Call Call Call |
|
Returns the SAX If dependencies from other processes are not available at this time, then return |
|
Returns the SAX If you do not override this method, then the JAXB processor uses the default error handler implemented by this class to handle SAX errors. |
See Also: Oracle Database XML Java API Reference to learn about theoracle.xml.pipeline.processes package |
This section contains the following topics:
The XML Pipeline processor is accessible through the following packages:
oracle.xml.pipeline.controller
, which provides an XML Pipeline controller that executes XML processes in a pipeline based on dependencies.
oracle.xml.pipeline.processes
, which provides wrapper classes for XML processes that can be executed by the XML Pipeline controller. The oracle.xml.pipeline.processes
package contains the classes that you can use to design a pipeline application framework. Each class extends the oracle.xml.pipeline.controller.Process
class.
Table 9-2 lists the components in the package. You can connect these components and processes through a combination of the XML Pipeline processor and a pipeline document.
Table 9-2 Classes in oracle.xml.pipeline.processes
Class | Description |
---|---|
|
Receives compressed XML and outputs parsed XML. |
|
Receives XML parsed with DOM or SAX and outputs compressed XML. |
|
Parses incoming XML and outputs a DOM tree. |
|
Parses incoming XML and outputs SAX events. |
|
Accepts a DOM as input, uses an XPath pattern to select one or more nodes from an XML |
|
Parses an XML schema and outputs a schema object for validation. This process is built into the XML Pipeline processor and builds schema objects used for validating XML documents. |
|
Validates against a local schema, analyzes the results, and reports errors if necessary. |
|
Accepts DOM as input, applies an XSL stylesheet, and outputs the result of the transformation. |
|
Receives an XSL stylesheet as a stream or DOM and creates an |
Figure 9-2 illustrates how to pass a pipeline document to a Java application that uses the XML Pipeline processor, configure the processor, and execute the pipeline.
Figure 9-2 Using the Pipeline Processor for Java
The basic steps are as follows:
Instantiate a pipeline document, which forms the input to the pipeline execution. Create the object by passing a FileReader
to the constructor as follows:
PipelineDoc pipe; FileReader f; pipe = new PipelineDoc((Reader)f, false);
Instantiate a pipeline processor. PipelineProcessor
is the top-level class that executes the pipeline. Table 9-3 describes some of the available methods.
Table 9-3 PipelineProcessor Methods
Method | Description |
---|---|
|
Executes the pipeline based on the |
|
Gets the type of execution mode: |
|
Sets the error handler for the pipeline. This call is mandatory to execute the pipeline. |
|
Sets the execution mode. |
|
Sets execution behavior. If |
|
Sets the |
The following statement instantiates the pipeline processor:
proc = new PipelineProcessor();
Set the processor to the pipeline document. For example:
proc.setPipelineDoc(pipe);
Set the execution mode for the processor and perform any other needed configuration. For example, set the mode by passing a constant to PipelineProcessor.setExecutionMode()
.
The following statement specifies sequential execution:
proc.setExecutionMode(PipelineConstants.PIPELINE_SEQUENTIAL);
Instantiate an error handler. The error handler must implement the PipelineErrorHandler
interface. For example:
errHandler = new PipelineSampleErrHdlr(logname);
Set the error handler for the processor by invoking setErrorHandler()
. For example:
proc.setErrorHandler(errHandler);
Execute the pipeline. For example:
proc.executePipeline();
Demo programs for the XML Pipeline processor are included in $ORACLE_HOME/xdk/demo/java/pipeline
. Table 9-4 describes the XML files and Java source files that you can use to test the utility.
Table 9-4 Pipeline Processor Sample Files
File | Description |
---|---|
|
A text file that describes how to set up the Pipeline processor demos. |
|
A sample Pipeline processor application. The program takes |
|
A sample program to create an error handler used by |
|
A sample XML document that describes a series of books. This document is specified as an input by |
|
An XSLT stylesheet that transforms the list of books in |
|
An XSLT stylesheet specified as an input by the |
|
An XSLT stylesheet specified as an input by the |
|
An XML schema document specified as an input by the |
|
A pipeline document. This document specifies that process p1 should parse |
|
A pipeline document. This document specifies that process p1 should parse |
|
A pipeline document. This document specifies that a process p5 should parse |
|
A pipeline document. This document specifies that process p1 should parse |
|
A sample XML document that describes a purchase order. This document is specified as an input by |
Documentation for how to compile and run the sample programs is located in the README
. The basic steps are as follows:
Change into the $ORACLE_HOME/xdk/demo/java/pipeline
directory (UNIX) or %ORACLE_HOME%\xdk\demo\java\pipeline
directory (Windows).
Make sure that your environment variables are set as described in "Setting Up the Java XDK Environment".
Run make
(UNIX) or Make.bat
(Windows) at the system prompt to generate class files for PipelineSample.java
and PipelineSampleErrHdler.java
and run the demo programs. The programs write output files to the log
subdirectory.
Alternatively, you can run the demo programs manually by using the following syntax:
java PipelineSample pipedoc pipelog [ seq | para ]
The pipedoc
option specifies which pipeline document to use. The pipelog
option specifies the name of the pipeline log file, which is optional unless you specify seq
or para
, in which case a filename is required. If you do not specify a log file, then the program generates pipeline.log
by default. The seq
option processes threads sequentially; para
processes in parallel. If you specify neither seq
or para
, then the default is parallel processing.
View the files generated from the pipeline, which are all named with the initial string myresult
, and the log files.
The command-line interface for the XML Pipeline processor is named orapipe
. The Pipeline processor is packaged with Oracle database. By default, the Oracle Universal Installer installs the utility on disk in $ORACLE_HOME/bin
.
Before running the utility for the first time, make sure that your environment variables are set as described in "Setting Up the Java XDK Environment". Run orapipe
at the operating system command line with the following syntax:
orapipe options pipedoc
The pipedoc
is the pipeline document, which is required. Table 9-5 describes the available options for the orapipe
utility.
Table 9-5 orapipe Command-Line Options
Option | Purpose |
---|---|
|
Prints the help message |
|
Writes errors and messages to the specified log file. The default is |
|
Does not log informational items. The default is on. |
|
Does not log warnings. The default is on. |
|
Validates the input |
|
Prints the release version. |
|
Executes the pipeline in sequential mode. The default is parallel. |
|
Executes pipeline even if target is up-to-date. By default no force is specified. |
|
Sets the value of |
This section contains the following topics:
To use the Oracle XML Pipeline processor, you must create an XML document according to the rules of the Pipeline Definition Language specified in the W3C Note.
The W3C specification defines the XML processing components and the inputs and outputs for these processes. The XML Pipeline processor includes support for the following XDK components:
XML parser
XML compressor
XML Schema validator
XSLT processor
The XML Pipeline processor executes a sequence of XML processing according to the rules in the pipeline document and returns a result. Example 9-1 shows pipedoc.xml
, which is a sample pipeline document included in the demo directory.
Example 9-1 pipedoc.xml
<pipeline xmlns="http://www.w3.org/2002/02/xml-pipeline" xml:base="http://example.org/"> <param name="target" select="myresult.html"/> <processdef name="domparser.p" definition="oracle.xml.pipeline.processes.DOMParserProcess"/> <processdef name="xslstylesheet.p" definition="oracle.xml.pipeline.processes.XSLStylesheetProcess"/> <processdef name="xslprocess.p" definition="oracle.xml.pipeline.processes.XSLProcess"/> <process id="p2" type="xslstylesheet.p" ignore-errors="false"> <input name="xsl" label="book.xsl"/> <outparam name="stylesheet" label="xslstyle"/> </process> <process id="p3" type="xslprocess.p" ignore-errors="false"> <param name="stylesheet" label="xslstyle"/> <input name="document" label="xmldoc"/> <output name="result" label="myresult.html"/> </process> <process id="p1" type="domparser.p" ignore-errors="true"> <input name="xmlsource" label="book.xml "/> <output name="dom" label="xmldoc"/> <param name="preserveWhitespace" select="true"></param> <error name="dom"> <html xmlns="http://www/w3/org/1999/xhtml"> <head> <title>DOMParser Failure!</title> </head> <body> <h1>Error parsing document</h1> </body> </html> </error> </process> </pipeline>
In Example 9-1, three processes are called and associated with Java classes in the oracle.xml.pipeline.processes
package. The pipeline document uses the <processdef/>
element to make the following associations:
domparser.p
is associated with the DOMParserProcess
class
xslstylesheet.p
is associated with the XSLStylesheetProcess
class
xslprocess.p
is associated with the XSLProcess
class
The PipelineSample
program accepts the pipedoc.xml
document shown in Example 9-1 as input along with XML documents book.xml
and book.xsl
. The basic design of the pipeline is as follows:
Parse the incoming book.xml
document and generate a DOM tree. This task is performed by DOMParserProcess
.
Parse book.xsl
as a stream and generate an XSLStylesheet
object. This task is performed by XSLStylesheetProcess
.
Receive the DOM of book.xml
as input, apply the stylesheet object, and write the result to myresult.html
. This task is performed by XSLProcess
.
Note the following aspects of the processing architecture used in the pipeline document:
The target information set, http://example.org/myresult.html
, is inferred from the default value of the target
parameter and the xml:base
setting.
The process p2
has an input of book.xsl
and an output parameter with the label xslstyle
, so it has to run to produce the input for p3
.
The p3
process depends on input parameter xslstyle
and document xmldoc
.
The p3
process has an output parameter with the label http://example.org/myresult.html
, so it has to run to produce the target.
The process p1
depends on input document book.xml
and outputs xmldoc
, so it has to run to produce the input for p3
.
In Example 9-1, more than one order of processing can satisfy all of the dependencies. Given the rules, the XML Pipeline processor must process p3
last but can process p1
and p2
in either order or process them in parallel.
The PipelineSample.java
source file illustrates a basic pipeline application. You can use the application with any of the pipeline documents in Table 9-4 to parse and transform an input XML document.
The basic steps of the program are as follows:
Perform the initial setup. The program declares references of type FileReader
(for the input XML file), PipelineDoc
(for the input pipeline document), and PipelineProcessor
(for the processor). The first argument is the pipeline document, which is required. If a second argument is received, then it is stored in the logname
String. The following code fragment illustrates this technique:
public static void main(String[] args) { FileReader f; PipelineDoc pipe; PipelineProcessor proc; if (args.length < 1) { System.out.println("First argument needed, other arguments are ". "optional:"); System.out.println("pipedoc.xml <output_log> <'seq'>"); return; } if (args.length > 1) logname = args[1]; ...
Create a FileReader
object by passing the first command-line argument to the constructor as the filename. For example:
f = new FileReader(args[0]);
Create a PipelineDoc
object by passing the reference to the FileReader
object. The following example casts the FileReader
to a Reader
and specifies no validation:
pipe = new PipelineDoc((Reader)f, false);
Instantiate an XML Pipeline processor. The following statement instantiates the pipeline processor:
proc = new PipelineProcessor();
Set the processor to the pipeline document. For example:
proc.setPipelineDoc(pipe);
Set the execution mode for the processor and perform any other configuration. The following code fragment uses a condition to determine the execution mode. If three or more arguments are passed to the program, then it sets the mode to sequential or parallel depending on which argument is passed. For example:
String execMode = null; if (args.length > 2) { execMode = args[2]; if(execMode.startsWith("seq")) proc.setExecutionMode(PipelineConstants.PIPELINE_SEQUENTIAL); else if (execMode.startsWith("para")) proc.setExecutionMode(PipelineConstants.PIPELINE_PARALLEL); }
Instantiate an error handler. The error handler must implement the PipelineErrorHandler
interface. The program uses the PipelineSampleErrHdler
shown in PipelineSampleErrHdlr.java
. The following code fragment illustrates this technique:
errHandler = new PipelineSampleErrHdlr(logname);
Set the error handler for the processor by invoking setErrorHandler()
. The following statement illustrates this technique:
proc.setErrorHandler(errHandler);
Execute the pipeline. The following statement illustrates this technique:
proc.executePipeline();
An application calling the XML Pipeline processor must implement the PipelineErrorHandler
interface to handle errors received from the processor. Set the error handler in the processor by calling setErrorHandler()
. When writing the error handler, you can choose to throw an exception for different types of errors.
The oracle.xml.pipeline.controller.PipelineErrorHandler
interface declares the methods shown in Table 9-6, all of which return void
.
Table 9-6 PipelineErrorHandler Methods
Method | Description |
---|---|
|
Handles |
|
Handles fatal |
|
Handles |
|
Prints optional, additional information about errors. |
The first three methods in Table 9-6 receive a reference to an oracle.xml.pipeline.controller.PipelineException
object. The following methods of the PipelineException
class are especially useful:
getExceptionType()
, which obtains the type of exception thrown
getProcessId()
, which obtains the process ID where the exception occurred
getMessage()
, which returns the message string of this Throwable
error
The PipelineSampleErrHdler.java
source file implements a basic error handler for use with the PipelineSample
program. The basic steps are as follows:
Implement a constructor. The constructor accepts the name of a log file and wraps it in a FileWriter
object as follows:
PipelineSampleErrHdlr(String logFile) throws IOException { log = new PrintWriter(new FileWriter(logFile)); }
Implement the error()
method. This implementation prints the process ID, exception type, and error message. It also increments a variable holding the error count. For example:
public void error (String msg, PipelineException e) throws Exception { log.println("\nError in: " + e.getProcessId()); log.println("Type: " + e.getExceptionType()); log.println("Message: " + e.getMessage()); log.println("Error message: " + msg); log.flush(); errCount++; }
Implement the fatalError()
method. This implementation follows the pattern of error()
. For example:
public void fatalError (String msg, PipelineException e) throws Exception { log.println("\nFatalError in: " + e.getProcessId()); log.println("Type: " + e.getExceptionType()); log.println("Message: " + e.getMessage()); log.println("Error message: " + msg); log.flush(); errCount++; }
Implement the warning()
method. This implementation follows the basic pattern of error()
except it increments the warnCount
variable rather than the errCount
variable. For example:
public void warning (String msg, PipelineException e) throws Exception { log.println("\nWarning in: " + e.getProcessId()); log.println("Message: " + e.getMessage()); log.println("Error message: " + msg); log.flush(); warnCount++; }
Implement the info()
method. Unlike the preceding methods, this method does not receive a PipelineException
reference as input. The following implementation prints the String
received by the method and increments the value of the warnCount
variable:
public void info (String msg) { log.println("\nInfo : " + msg); log.flush(); warnCount++; }
Implement a method to close the PrintWriter
. The following code implements the method closeLog()
, which prints the number of errors and warnings and calls PrintWriter.close()
:
public void closeLog() { log.println("\nTotal Errors: " + errCount + "\nTotal Warnings: " + warnCount); log.flush(); log.close(); }
See Also: Oracle Database XML Java API Reference to learn about thePipelineErrorHandler interface and the PipelineException class |
The following sections describe features introduced or changed in this manual:
DOM Stream access to XML nodes is done by PL/SQL and Java APIs. Nodes in an XML document can now exceed 64 KBytes by a large amount.
The new XDK compact binary XML processors provide an encoder, a decoder, and a token manager to convert the schema or non-schema-based stream to and from XML 1.0 text and SAX events. The format is the same used in Oracle XML DB Developer's Guide.
Binary XML adds a third storage model for persistent XML in the database: binary XML. Java and C APIs, and PL/SQL packages are affected. Binary XML support in the C API is used for both XML Developer's Kit and XML DB.
Support is now provided for a scalable, pluggable DOM in Java:
Scalable DOM
support for Java includes lazy loading of DOM
nodes, DOM
updates of binary XML, multiple applications sharing the same DOM
source, binary XML as output, and shadow copy in DOM
.
Pluggable DOM splits the DOM implementation into two separate layers: DOM
API layer and data layer. The data is either internal or plug-in, and are accessed through an implementation of the InfosetReader
interface.
Configurable support for Java DOM is provided.
The Unified Java API for XML allows mid-tier Java programs to leverage all the benefits of XMLType
used with a session pool model of connection management. This allows XMLType
object to be disconnected from the database session used to create it.
JAXP 1.3 support for XPath
with extensions improves Java XSLT
performance. Support is for static and dynamic context and users can register runtime context.
HTTP
server for SOA
is enabled. The database is capable of exposing PL/SQL packages, procedures, and functions as Web Services. The database is capable of executing dynamic XQuery
and SQL
queries.
Chapters on SOAP for Java and C++ were removed.
XmlDiff
for C detects the differences between two XML documents and represents the difference in XML. XmlPatch
outputs the differences and applies the changes on the target XML document.
The JSR 170 standard is supported.
The C Pull Parser reduces memory overhead compared to the SAX model.
Streaming Validator support for C improves XML processing.
Document Updates For DLF/TransX is enhanced.
The orastream functions in the XDK for C enable you to access large nodes.
Oracle recommends discontinuing the use of the following features in new applications. These features are supported in the current release, but they may be deprecated in a future release. In particular:
Do not create an XMLIndex on the XML DB repository.
Do not use the XSQL feature with XML DB applications.
Do not use encoding types as specified in Chapter 5, "Using Binary XML for Java", in these sections:
For improved performance, consider using the PL/SQL packages DBMS_XMLGen and DBMS_XMLStore, which are written in C and built into the database, rather than the DBMS_XMLQuery and DBMS_XMLSave packages as specified in Chapter 11, Using XSU: Basic Process.
See Also: Oracle XML DB Developer's Guide for more information about deprecated Oracle XML DB constructs |
This chapter contains these topics:
This section contains the following topics:
XSLT is an XML-based language that you can use to transform one XML document into another text document. For example, you can use XSLT to accept an XML data document as input, perform arithmetic calculations on element values in the document, and generate an XHTML document that shows the calculation results.In XSLT, XPath is used to navigate and process elements in the source node tree. XPath models an XML document as a tree made up of nodes; the types of nodes in the XPath node tree correspond to the types of nodes in a DOM tree.
This chapter assumes that you are familiar with the following W3C standards:
eXtensible Stylesheet Language (XSL) and eXtensible Stylesheet Language Transformation (XSLT). If you require a general introduction to XSLT, consult the XML resources listed in "Related Documents" of the preface.
XSLT is currently available in two versions: a working draft for XSLT 2.0 and the XSLT 1.0 Recommendation. You can find the specifications at the following URLs:
XPath, which is the navigational language used by XSLT and other XML languages, is available in two versions: a working draft for XPath 2.0 and the XPath 1.0 Recommendation. You can find the specifications for the two XPath versions at the following URLs:
Oracle XDK XSLT processor implements both the XSLT and XPath 1.0 standards as well as the current working drafts of the XSLT and XPath 2.0 standards. The XDK XSLT processor supports the XPath 2.0 functions and operators. You can find the specification at the following URL:
http://www.w3.org/TR/xpath-functions/
In Oracle Database 10g, the XDK provides several useful features not included in XSLT 1.0. To use XSLT 2.0, set the version
attribute in your stylesheet as follows:
<? xml-stylesheet version="2.0" ... ?>
Some of the most useful XSLT 2.0 features are the following:
User-defined functions
You can use the <xsl:function>
declaration to define functions. This element must have one name
attribute to define the function name. The value of the name
attribute is a QName
. The content of the <xsl:function>
element is zero or more xsl:param
elements that specify the formal arguments of the function, followed by a sequence constructor that defines the value returned by the function.
Note that QName
can have a null namespace, but user-defined functions must have a non-null namespace. That is, if abc
is defined as a namespace, then add
is not a legal user-defined function, but abc:add
is.
Grouping
You can use the <xsl:for-each-group>
element, current-group()
function, and current-grouping-key()
function to group items.
Multiple result documents
You can use the <xsl:result-document>
element to create a result tree. The content of the <xsl:result-document>
element is a sequence constructor for the children of the document node of the tree.
For example, this element enables you to accept an XML document as input and break it into separate documents. You can take an XML document that describes a list of books and generate an XHTML document for each book. You can then validate each output document.
Temporary trees
Instead of representing the intermediate XSL transformation results and XSL variables as strings, as in XSLT 1.0, you can store them as a set of document nodes. The document nodes, which you can construct with the <xsl:variable>
, <xsl:param>
, and <xsl:with-param>
elements, are called temporary trees.
Character mapping
In XSLT 1.0, you had to use the disable-output-escaping
attribute of the <xsl:text>
and <xsl:value-of>
elements to specify character escaping. In XSLT 2.0, you can declare mapping characters with an <xsl:character-map>
element as a top level stylesheet element. You can use this element to generate files with reserved or invalid XML characters in the XSLT outputs, such as <
, >
, and &
.
The Oracle XDK XSLT processor is a software program that transforms an XML document into another text-based format. For example, the processor can transform XML into XML, HTML, XHTML, or text. You can invoke the processor programmatically by using the APIs or run it from the command line. The XSLT processor can perform the following tasks:
Reads one or more XSLT stylesheets. The processor can apply multiple stylesheets to a single XML input document and generate different results.
Reads one or more input XML documents. The processor can use a single stylesheet to transform multiple XML input documents.
Builds output documents by applying the rules in the stylesheet to the input XML documents. The output is a DOM tree, output stream, or series of SAX events.
Whereas XSLT is a function-based language that generally requires a DOM of the input document and stylesheet to perform the transformation, the Java XDK implementation of the XSLT processor can use SAX to create a stylesheet object to perform transformations with higher efficiency and fewer resources. You can reuse this stylesheet object to transform multiple documents without reparsing the stylesheet.
Figure 6-1 depicts the basic design of the XSLT processor for Java.
See Also: Oracle Database XML Java API Reference to learn about theXMLParser and XSDBuilder classes |
Figure 6-1 Using the XSLT Processor for Java
Demo programs for the XSLT processor for Java are included in $ORACLE_HOME/xdk/demo/java/parser/xslt
. Table 6-1 describes the XML files and programs that you can use to test the XSLT processor.
Table 6-1 XSLT Processor Sample Files
File | Description |
---|---|
|
A sample XML document that you can use to test ID selection and pattern matching. Its associated stylesheet is |
|
A sample stylesheet for use with |
|
A sample XML data document that you can use to perform simple arithmetic. Its associated stylesheet is |
|
A sample stylesheet for use with |
|
A sample XML data document that you can use to test for source tree numbering. The document describes the structure of a book. |
|
A sample stylesheet for us with |
|
A sample XML data document that you can use to test for |
|
A sample stylesheet for use with |
|
A sample XML data document that you can use with |
|
A sample stylesheet for us with |
|
A sample XML data document that you can use to test perform various string test and manipulations. Its associated stylesheet is |
|
A sample stylesheet for us with |
|
A stylesheet that provides the framework for an HTML page. The stylesheet is included by |
|
A sample XML data document that you can use to test the use of XSL variables. The document describes the structure of a book. Its associated stylesheet is |
|
A stylesheet for use with |
|
A sample application that offers a simple example of how to use the XSL processing capabilities of the Oracle XSLT processor. The program transforms an input XML document by using an input stylesheet. This program builds the result of XSL transformations as a Run this program with any XSLT stylesheet in the directory as a first argument and its associated |
|
A sample application that offers a simple example of how to use the XSL processing capabilities of the Oracle XSLT processor. The program transforms an input XML document by using an input stylesheet. This program outputs the result to a stream and supports |
Documentation for how to compile and run the sample programs is located in the README
. The basic steps are as follows:
Change into the $ORACLE_HOME/xdk/demo/java/parser/xslt
directory (UNIX) or %ORACLE_HOME%\xdk\demo\java\parser\xslt
directory (Windows).
Make sure that your environment variables are set as described in "Setting Up the Java XDK Environment".
Run make
(UNIX) or Make.bat
(Windows) at the command line. The make file compiles the source code and then runs the XSLSample
and XSLSample2
programs for each *.xml
file and its associated *.xsl
stylesheet. The program writes its output for each transformation to *.out
.
You can view the *.out
files to see the output for the XML transformations. You can also run the programs on the command line as follows, where name
is replaced by match
, math
, and so forth:
java XSLSample name.xsl name.xml java XSLSample2 name.xsl name.xml
For example, run the match.xml
demos as follows:
java XSLSample match.xsl match.xml java XSLSample2 match.xsl match.xml
The XDK includes oraxsl
, which is a command-line Java interface that can apply a stylesheet to multiple XML documents. The $ORACLE_HOME/bin/oraxsl
and %ORACLE_HOME%\bin\oraxsl.bat
shell scripts execute the oracle.xml.jaxb.oraxsl
class. To use oraxsl
ensure that your CLASSPATH
is set as described in "Setting Up the Java XDK Environment".
Use the following syntax on the command line to invoke oraxsl
:
oraxsl options source stylesheet result
The oraxsl
utility expects a stylesheet, an XML file to transform, and an optional result file. If you do not specify a result file, then the utility sends the transformed document to standard output. If multiple XML documents need to be transformed by a stylesheet, then use the -l
or -d
options in conjunction with the -s
and -r
options. These and other options are described in Table 6-2.
Table 6-2 Command Line Options for oraxsl
Option | Description |
---|---|
|
Shows warnings. By default, warnings are turned off. |
|
Specifies file into which the program writes errors and warnings. |
|
Lists files to be processed. |
|
Specifies the directory that contains the files to transform. The default behavior is to process all files in the directory. If only a subset of the files in that directory, for example, one file, need to be processed, then change this behavior by setting |
|
Specifies extensions for the files that should be excluded. Use this option in conjunction with |
|
Specifies extensions for the files that should be included. Use this option in conjunction with |
|
Specifies the stylesheet. If you set |
|
Specifies the extension to use for results. If you set |
|
Specifies the directory in which to place results. You must set this option in conjunction with the |
|
Lists parameters. |
|
Specifies the number of threads to use for processing. Using multiple threads can provide performance improvements when processing multiple documents. |
|
Generates verbose output. The program prints some debugging information and can help in tracing any problems that are encountered during processing. |
|
Generates debugging output. By default, debug mode is disabled. Note that a GUI version of the XSLT debugger is available in Oracle JDeveloper. |
You can test oraxsl
on the various XML files and stylesheets in $ORACLE_HOME/xdk/demo/java/parser/xslt
. Example 6-1 displays the contents of math.xml
.
Example 6-1 math.xml
<?xml version="1.0"?> <doc> <n1>5</n1> <n2>2</n2> <div>-5</div> <mod>2</mod> </doc>
The XSLT stylesheet named math.xsl
is shown in Example 6-2.
Example 6-2 math.xsl
<?xml version="1.0"?><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="doc"> <HTML> <H1>Test for mod.</H1> <HR/> <P>Should say "1": <xsl:value-of select="5 mod 2"/></P> <P>Should say "1": <xsl:value-of select="n1 mod n2"/></P> <P>Should say "-1": <xsl:value-of select="div mod mod"/></P> <P><xsl:value-of select="div or ((mod)) | or"/></P> </HTML> </xsl:template> </xsl:stylesheet
You can run the oraxsl
utility on these files to produce HTML output as shown in the following example:
oraxsl math.xml math.xsl math.htm
The output file math.htm
is shown in Example 6-3.
This section contains the following topics:
As explained in "Using the XSLT Processor for Java: Overview", the fundamental classes used by the XSLT processor are DOMParser
and XSLProcessor
. The XSL2Sample.java
demo program provides a good illustration of how to use these classes to transform an XML document with an XSLT stylesheet.
Use the following basic steps to write Java programs that use the XSLT processor:
Create a DOM parser object that you can use to parse the XML data documents and XSLT stylesheets. The following code fragment from XSL2Sample.java
illustrates how to instantiate a parser:
XMLDocument xml, xsldoc, out;URL xslURL;URL xmlURL; // ... parser = new DOMParser();parser.setPreserveWhitespace(true);
Note that by default, the parser does not preserve whitespace unless a DTD is used. It is important to preserrve whitespace because it enables XSLT whitespace rules to determine how whitespace is handled.
Parse the XSLT stylesheet with the DOMParser.parse()
method. The following code fragment from XSL2Sample.java
illustrates how to perform the parse:
xslURL = DemoUtil.createURL(args[0]); parser.parse(xslURL); xsldoc = parser.getDocument();
Parse the XML data document with the DOMParser.parse()
method. The following code fragment from XSL2Sample.java
illustrates how to perform the parse:
xmlURL = DemoUtil.createURL(args[1]); parser.parse(xmlURL); xml = parser.getDocument();
Create a new XSLT stylesheet object. You can pass objects of the following classes to the XSLProcessor.newXSLStylesheet()
method:
java.io.Reader
java.io.InputStream
XMLDocument
java.net.URL
For example, XSL2Sample.java
illustrates how to create a stylesheet object from an XMLDocument
object:
XSLProcessor processor = new XSLProcessor(); processor.setBaseURL(xslURL); XSLStylesheet xsl = processor.newXSLStylesheet(xsldoc);
Set the XSLT processor to display any warnings. For example, XSL2Sample.java
calls the showWarnings()
and setErrorStream()
methods as follows:
processor.showWarnings(true); processor.setErrorStream(System.err);
Use the XSLProcessor.processXSL()
method to apply the stylesheet to the input XML data document. Table 6-3 lists some of the other available XSLProcessor
methods.
Table 6-3 XSLProcessor Methods
Method | Description |
---|---|
|
Removes parameters. |
|
Resets all parameters. |
|
Sets parameters for the transformation. |
|
Sets a base URL for any relative references in the stylesheet. |
|
Sets an entity resolver for any relative references in the stylesheet. |
|
Sets a locale for error reporting. |
The following code fragment from XSL2Sample.java
shows how to apply the stylesheet to the XML document:
processor.processXSL(xsl, xml, System.out);
Process the transformed output. You can transform the results by creating an XML document object, writing to an output stream, or reporting SAX events.
The following code fragment from XSL2Sample.java
shows how to print the results:
processor.processXSL(xsl, xml, System.out);
The XSLSample.java
demo program illustrates how to generate an oracle.xml.parser.v2.XMLDocumentFragment
object as the result of an XSL transformation. An XMLDocumentFragment
is a "lightweight" Document
object that extracts a portion of an XML document tree. The XMLDocumentFragment
class implements the org.w3c.dom.DocumentFragment
interface.
The XSL2Sample.java
program illustrates how to generate a DocumentFragment
object. The basic steps for transforming XML are the same as those described in "Performing Basic XSL Transformation". The only difference is in the arguments passed to the XSLProcessor.processXSL()
method. The following code fragment from XSL2Sample.java
shows how to create the DOM fragment and then print it to standard output:
XMLDocumentFragment result = processor.processXSL(xsl, xml); result.print(System.out);
Table 6-4 lists some of the XMLDocumentFragment
methods that you can use to manipulate the object.
Table 6-4 XMLDocumentFragment Methods
Method | Description |
---|---|
|
Gets a |
|
Gets the local name for this element |
|
Gets the namespace URI of this element |
|
Gets the node immediately following the current node |
|
Gets the name of the node |
|
Gets a code that represents the type of the underlying object |
|
Gets the parent of the current node |
|
Gets the node immediately preceding the current node |
|
Reports SAX events from a DOM Tree |
This section contains these topics:
The XSLT 1.0 standard defines two kinds of extensions: extension elements and extension functions. The XDK provides extension functions for XSLT processing that enable users of the XSLT processor to call any Java method from XSL expressions. Note the following guidelines when using Oracle XSLT extensions:
When you define an XSLT extension in a given programming language, you can only use the XSLT stylesheet with XSLT processors that can invoke this extension. Thus, only the Java version of the processor can invoke extension functions that are defined in Java.
Use XSLT extensions only if the built-in XSL functions cannot solve a given problem.
As explained in the following section, the namespace of the extension class must start with the proper URL.
The following Oracle extension functions are particularly useful:
<ora:output>
, you can use <ora:output>
as a top-level element or in an XSL template. If used as a top-level element, it is similar to the <xsl:output>
extension function, except that it has an additional name
attribute. When used as a template, it has the additional attributes use
and href
. This function is useful for creating multiple outputs from one XSL transformation.
<ora:node-set>
, which converts a result tree fragment into a node-set. This function is useful when you want to refer the existing text or intermediate text results in XSL for further transformation.
The Oracle Java extension functions belong to the namespace that corresponds to the following URI:
http://www.oracle.com/XSL/Transform/java/
An extension function that belongs to the following namespace refers to methods in the Java classname
, so that you can construct URIs in the following format:
http://www.oracle.com/XSL/Transform/java/classname
For example, you can use the following namespace to call java.lang.String
methods from XSL expressions:
http://www.oracle.com/XSL/Transform/java/java.lang.String
Note: When assigning thexsl prefix to a namespace, the correct URI is xmlns:xsl="http://www.w3.org/1999/XSL/Transform" . Any other URI fails to give correct output. |
If the Java method is a non-static method of the class, then the first parameter is used as the instance on which the method is invoked, and the rest of the parameters are passed to the method. If the extension function is a static method, however, then all the parameters of the extension function are passed as parameters to the static function. Example 6-4 shows how to use the java.lang.Math.ceil()
method in an XSLT stylesheet.
Example 6-4 Using a Static Function in an XSLT Stylesheet
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:math="http://www.oracle.com/XSL/Transform/java/java.lang.Math"> <xsl:template match="/"> <xsl:value-of select="math:ceil('12.34')"/> </xsl:template> </xsl:stylesheet>
For example, you can create Example 6-4 as stylesheet ceil.xsl
and then apply it to any well-formed XML document. For example, run the oraxsl
utility as follows:
oraxsl ceil.xsl ceil.xsl ceil.out
The output document ceil.out
has the following content:
<?xml version = '1.0' encoding = 'UTF-8'?> 13
Note: The XSL class loader only knows about statically added JARs and paths in theCLASSPATH as well as those specified by wrapper.classpath . Files added dynamically are not visible to XSLT processor. |
The extension function new
creates a new instance of the class and acts as the constructor. Example 6-5 creates a new String
object with the value "Hello World," stores it in the XSL variable str1
, and then outputs it in uppercase.
Example 6-5 Using a Constructor in an XSLT Stylesheet
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:jstring="http://www.oracle.com/XSL/Transform/java/java.lang.String"> <xsl:template match="/"> <!-- creates a new java.lang.String and stores it in the variable str1 --> <xsl:variable name="str1" select="jstring:new('HeLlO wOrLd')"/> <xsl:value-of select="jstring:toUpperCase($str1)"/> </xsl:template> </xsl:stylesheet>
For example, you can create this stylesheet as hello.xsl
and apply it to any well-formed XML document. For example, run the oraxsl
utility as follows:
oraxsl hello.xsl hello.xsl hello.out
The output document hello.out
has the following content:
<?xml version = '1.0' encoding = 'UTF-8'?> HELLO WORLD
The result of an extension function can be of any type, including the five types defined in XSL and the additional simple XML Schema data types defined in XSLT 2.0:
NodeSet
Boolean
String
Number
ResultTree
You can store these data types in variables or pass to other extension functions. If the result is of one of the five types defined in XSL, then the result can be returned as the result of an XSL expression.
The XSLT Processor supports overloading based on the number of parameters and type. The processor performs implicit type conversion between the five XSL types as defined in XSL. It performs type conversion implicitly among the following datatypes, and also from NodeSet
to the following datatypes:
String
Number
Boolean
ResultTree
Overloading based on two types that can be implicitly converted to each other is not permitted. The following overloading results in an error in XSL because String
and Number
can be implicitly converted to each other:
overloadme(int i){}
overloadme(String s){}
Mapping between XSL datatypes and Java datatypes is done as follows:
String -> java.lang.String Number -> int, float, double Boolean -> boolean NodeSet -> NodeList ResultTree -> XMLDocumentFragment
The stylesheet in Example 6-6 parses the variable.xml
document, which is located in the directory $ORACLE_HOME/xdk/demo/java/parser/xslt
, and retrieves the value of the <title>
child of the <chapter>
element.
Example 6-6 gettitle.xsl
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:parser = "http://www.oracle.com/XSL/Transform/java/oracle.xml.parser.v2.DOMParser" xmlns:document = "http://www.oracle.com/XSL/Transform/java/oracle.xml.parser.v2.XMLDocument"> <xsl:template match ="/"> <!-- Create a new instance of the parser and store it in myparser variable --> <xsl:variable name="myparser" select="parser:new()"/> <!-- Call an instance method of DOMParser. The first parameter is the object. The PI is equivalent to $myparser.parse('file:/my_path/variable.xml'). Note that you should replace my_path with the absolute path on your system. --> <xsl:value-of select="parser:parse($myparser, 'file:/my_path/variable.xml')"/> <!-- Get the document node of the XML Dom tree --> <xsl:variable name="mydocument" select="parser:getDocument($myparser)"/> <!-- Invoke getelementsbytagname on mydocument --> <xsl:for-each select="document:getElementsByTagName($mydocument,'chapter')"> The value of the title element is: <xsl:value-of select="docinfo/title" /> </xsl:for-each> </xsl:template> </xsl:stylesheet>
You can create Example 6-6 as gettitle.xsl
and then run oraxsl
as follows:
oraxsl gettitle.xsl gettitle.xsl variable.out
The output document variable.out
has the following content:
<?xml version = '1.0' encoding = 'UTF-8'?> The value of the title element is: Section Tests
This section lists XSL and XSLT Processor for Java hints, and contains these topics:
"Merging Documents with appendChild()" discusses the DOM technique for merging documents. If the merging operation is simple, then you can also use an XSLT-based approach. Suppose that you want to merge the XML documents in Example 6-7 and Example 6-8.
Example 6-7 msg_w_num.xml
<messages> <msg> <key>AAA</key> <num>01001</num> </msg> <msg> <key>BBB</key> <num>01011</num> </msg> </messages>
Example 6-8 msg_w_text.xml
<messages> <msg> <key>AAA</key> <text>This is a Message</text> </msg> <msg> <key>BBB</key> <text>This is another Message</text> </msg> </messages>
Example 6-9 displays a sample stylesheet that merges the two XML documents based on matching the <key/>
element values.
Example 6-9 msgmerge.xsl
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output indent="yes"/> <!-- store msg_w_text.xml in doc2 variable --> <xsl:variable name="doc2" select="document('msg_w_text.xml')"/> <!-- match each node in input xml document, that is, msg_w_num.xml --> <xsl:template match="@*|node()"> <!-- copy the current node to the result tree --> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <!-- match each <msg> element in msg_w_num.xml --> <xsl:template match="msg"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> <!-- insert two spaces so indentation is correct in output document --> <xsl:text> </xsl:text> <!-- copy <text> node from msg_w_text.xml into result tree --> <text><xsl:value-of select="$doc2/messages/msg[key=current()/key]/text"/> </text> </xsl:copy> </xsl:template> </xsl:stylesheet>
Create the XML files in Example 6-7, Example 6-8, and Example 6-9 and run the following at the command line:
oraxsl msg_w_num.xml msgmerge.xsl msgmerge.xml
Example 6-10 shows the output document, which merges the data contained in msg_w_num.xml
and msg_w_text.xml
.
Example 6-10 msgmerge.xml
<?xml version = '1.0' encoding = 'UTF-8'?> <messages> <msg> <key>AAA</key> <num>01001</num> <text>This is a Message</text> </msg> <msg> <key>BBB</key> <num>01011</num> <text>This is another Message</text> </msg> </messages>
This technique is not as efficient for larger files as an equivalent database join of two tables, but it is useful if you have only XML files to work with.
Suppose that you want to generate an HTML form for inputting data that uses column names from a database table. You can achieve this goal by using XSU to obtain an XML document based on the user_tab_columns
table and XSLT to transform the XML into an HTML form.
Use XSU to generate an XML document based on the columns in the table. For example, suppose that the table is hr.employees
. You can run XSU from the command line as follows:
java OracleXML getXML -user "hr/password"\
"SELECT column_name FROM user_tab_columns WHERE table_name = 'EMPLOYEES'"
Save the XSU output as an XML file called emp_columns.xml
. The XML should look like the following, with one <ROW>
element corresponding to each column in the table (some <ROW>
elements have been removed to conserve space):
<?xml version = '1.0'?><ROWSET> <ROW num="1"> <COLUMN_NAME>EMPLOYEE_ID</COLUMN_NAME> </ROW> <ROW num="2"> <COLUMN_NAME>FIRST_NAME</COLUMN_NAME> </ROW> <!-- rows 3 through 10 --> <ROW num="11"> <COLUMN_NAME>DEPARTMENT_ID</COLUMN_NAME> </ROW> </ROWSET>
Create a stylesheet to transform the XML into HTML. For example, create the columns.xsl
stylesheet as follows:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="html"/> <xsl:template match="/"> <HTML> <xsl:apply-templates select="@*|node()"/> </HTML> </xsl:template> <xsl:template match="ROW"> <xsl:value-of select="COLUMN_NAME"/> <xsl:text> </xsl:text> <INPUT NAME="{COLUMN_NAME}"/> <BR/> </xsl:template> </xsl:stylesheet>
Run the oraxsl
utility to generate the HTML form. For example:
oraxsl emp_columns.xml columns.xsl emp_form.htm
Review the output HTML form, which should have the following contents:
<HTML> EMPLOYEE_ID <INPUT NAME="EMPLOYEE_ID"><BR> FIRST_NAME <INPUT NAME="FIRST_NAME"><BR> LAST_NAME <INPUT NAME="LAST_NAME"><BR> EMAIL <INPUT NAME="EMAIL"><BR> PHONE_NUMBER <INPUT NAME="PHONE_NUMBER"><BR> HIRE_DATE <INPUT NAME="HIRE_DATE"><BR> JOB_ID <INPUT NAME="JOB_ID"><BR> SALARY <INPUT NAME="SALARY"><BR> COMMISSION_PCT <INPUT NAME="COMMISSION_PCT"><BR> MANAGER_ID <INPUT NAME="MANAGER_ID"><BR> DEPARTMENT_ID <INPUT NAME="DEPARTMENT_ID"><BR> </HTML>
Programmer's Guide
11g Release 2 (11.2)
E23582-01
July 2011
Oracle XML Developer's Kit Programmer's Guide, 11g Release 2 (11.2)
E23582-01
Copyright © 2001, 2011, Oracle and/or its affiliates. All rights reserved.
Primary Authors: Drew Adams, Lance Ashdown, Janis Greenberg, Jack Melnick, Sue Pelski
Contributing Authors: Steve Muench, Mark Scardina, Jinyu Wang
Contributors: Nipun Agarwal, Sivasankaran Chandrasekar, Dan Chiba, Steve Ding, Mark Drake, Bill Han, Bhushan Khaladkar, Roza Leyderman, Valarie Moore, Ravi Murthy, Anguel Novoselsky, Helen Slattery, Balu Sthanikam, Lu Sun, Asha Tarachandani, Tim Yu, Simon Wong, Kongyi Zhou
This software and related documentation are provided under a license agreement containing restrictions on use and disclosure and are protected by intellectual property laws. Except as expressly permitted in your license agreement or allowed by law, you may not use, copy, reproduce, translate, broadcast, modify, license, transmit, distribute, exhibit, perform, publish, or display any part, in any form, or by any means. Reverse engineering, disassembly, or decompilation of this software, unless required by law for interoperability, is prohibited.
The information contained herein is subject to change without notice and is not warranted to be error-free. If you find any errors, please report them to us in writing.
If this is software or related documentation that is delivered to the U.S. Government or anyone licensing it on behalf of the U.S. Government, the following notice is applicable:
U.S. GOVERNMENT RIGHTS Programs, software, databases, and related documentation and technical data delivered to U.S. Government customers are "commercial computer software" or "commercial technical data" pursuant to the applicable Federal Acquisition Regulation and agency-specific supplemental regulations. As such, the use, duplication, disclosure, modification, and adaptation shall be subject to the restrictions and license terms set forth in the applicable Government contract, and, to the extent applicable by the terms of the Government contract, the additional rights set forth in FAR 52.227-19, Commercial Computer Software License (December 2007). Oracle America, Inc., 500 Oracle Parkway, Redwood City, CA 94065.
This software or hardware is developed for general use in a variety of information management applications. It is not developed or intended for use in any inherently dangerous applications, including applications that may create a risk of personal injury. If you use this software or hardware in dangerous applications, then you shall be responsible to take all appropriate fail-safe, backup, redundancy, and other measures to ensure its safe use. Oracle Corporation and its affiliates disclaim any liability for any damages caused by use of this software or hardware in dangerous applications.
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.
Intel and Intel Xeon are trademarks or registered trademarks of Intel Corporation. All SPARC trademarks are used under license and are trademarks or registered trademarks of SPARC International, Inc. AMD, Opteron, the AMD logo, and the AMD Opteron logo are trademarks or registered trademarks of Advanced Micro Devices. UNIX is a registered trademark of The Open Group.
This software or hardware and documentation may provide access to or information on content, products, and services from third parties. Oracle Corporation and its affiliates are not responsible for and expressly disclaim all warranties of any kind with respect to third-party content, products, and services. Oracle Corporation and its affiliates will not be responsible for any loss, costs, or damages incurred due to your access to or use of third-party content, products, or services.
This chapter contains these topics:
Note: Use the new unified C API for new XDK and Oracle XML DB applications. The old C functions are deprecated and supported only for backward compatibility, but will not be enhanced. They will be removed in a future release.The new C API is described in Chapter 18, "Using the XML Parser for C". |
The Oracle XVM Package implements the XSL Transformation (XSLT) language as specified in the W3C Recommendation of 16 November 1999. The package includes XSLT Compiler and XSLT Virtual Machine (XVM). The implementation by Oracle of the XSLT compiler and the XVM enables compilation of XSLT (Version 1.0) into bytecode format, which is executed by the virtual machine. XSLT Virtual Machine is the software implementation of a "CPU" designed to run compiled XSLT code. The virtual machine assumes a compiler compiling XSLT stylesheets to a sequence of bytecodes or machine instructions for the "XSLT CPU". The bytecode program is a platform-independent sequence of 2-byte units. It can be stored, cached and run on different XVMs. The XVM uses the bytecode programs to transform instance XML documents. This approach clearly separates compile-time from run-time computations and specifies a uniform way of exchanging data between instructions. The benefits of this approach are:
An XSLT stylesheet can be compiled, saved in a file, and re-used often, even on different platforms.
The XVM is significantly faster and uses less memory than other XSLT processors.
The bytecodes are not language-dependent. There is no difference between code generated from a C or C++ XSLT compiler.
A typical scenario of using the package APIs has the following steps:
Create and use an XML meta-context object.
xctx = XmlCreate(&err,...);
Create and use an XSLT compiler object.
comp = XmlXvmCreateComp(xctx);
Compile an XSLT stylesheet or XPath expression and store or cache the resulting bytecode.
code = XmlXvmCompileFile(comp, xslFile, baseuri, flags, &err);
or
code = XmlXvmCompileDom (comp, xslDomdoc, flags, &err);
or
code = XmlXvmCompileXPath (comp, xpathexp, namespaces, &err);
Create and use an XVM object. The explicit stack size setting is needed when XVM terminates with a "Stack Overflow" message or when smaller memory footprints are required. See XmlXvmCreate()
.
vm = XmlXvmCreate(xctx, "StringStack", 32, "NodeStack", 24, NULL);
Set the output (optional). Default is a stream.
err = XmlXvmSetOutputDom (vm, NULL);
or
err = XmlXvmSetOutputStream(vm, &xvm_stream);
or
err = XmlXvmSetOutputSax(vm, &xvm_callback, NULL);
Set a stylesheet bytecode to the XVM object. Can be repeated with other bytecode.
len = XmlXvmGetBytecodeLength(code, &err); err = XmlXvmSetBytecodeBuffer(vm, code, len);
or
err = XmlXvmSetBytecodeFile (vm, xslBytecodeFile);
Transform an instance XML document or evaluate a compiled XPath expression. Can be repeated with the same or other XML documents.
err = XmlXvmTransformFile(vm, xmlFile, baseuri);
or
err = XmlXvmTransformDom (vm, xmlDomdoc);
or
obj = (xvmobj*)XmlXvmEvaluateXPath (vm, code, 1, 1, node);
Get the output tree fragment (if DOM output is set at step 5).
node = XmlXvmGetOutputDom (vm);
Delete the objects.
XmlXvmDestroy(vm); XmlXvmDestroyComp(comp); XmlDestroy(xctx);
The XVM processor is accessed from the command-line this way:
xvm
Usage:
xvm options xslfile xmlfile
xvm options xpath xmlfile
Options:
-c Compile xslfile. The bytecode is in "xmlfile.xvm". -ct Compile xslfile and transform xmlfile. -t Transform xmlfile using bytecode from xslfile. -xc Compile xpath. The bytecode is in "code.xvm". -xct Compile and evaluate xpath with xmlfile. -xt Evaluate XPath bytecode from xpath with xmlfile.
Examples:
xvm -ct db.xsl db.xml xvm -t db.xvm db.xml xvm -xct "doc/employee[15]/family" db.xml
Oracle XVM Processor for C is part of the standard installation of Oracle Database.
See Also: |
The Oracle XSL/XPath Package implements the XSL Transformation (XSLT) language as specified in the W3C Recommendation of 16 November 1999. The package includes the XSLT processor and XPath Processor. The Oracle implementation of the XSLT processor follows the more common design approach, which melts 'compiler' and 'processor' into one object.
A typical scenario of using the package APIs has the following steps:
Create and use an XML meta-context object.
xctx = XmlCreate(&err,...);
Parse the XSLT stylesheet.
xslDomdoc = XmlLoadDom(xctx, &err, "file", xslFile, "base_uri", baseuri, NULL);
Create an XSLT processor for the stylesheet
xslproc = XmlXslCreate (xctx, xslDomdoc, baseuri, &err);
Parse the instance XML document.
xmlDomdoc = XmlLoadDom(xctx, &err, "file", xmlFile, "base_uri", baseuri, NULL);
Set the output (optional). Default is DOM.
err = XmlXslSetOutputStream(xslproc, &stream);
Transform the XML document. This step can be repeated with the same or other XML documents.
err = XmlXslProcess (xslproc, xmlDomdoc, FALSE);
Get the output (if DOM).
node = XmlXslGetOutput(xslproc);
Delete objects.
XmlXslDestroy(xslproc); XmlDestroy(xctx);
A typical scenario of using the package APIs has the following steps:
Create and use an XML meta-context object.
xctx = XmlCreate(&err,...);
Parse the XML document or get the current node from already existing DOM.
node = XmlLoadDom(xctx, &err, "file", xmlFile, "base_uri", baseuri, NULL);
Create an XPath processor.
xptproc = XmlXPathCreateCtx(xctx, NULL, node, 0, NULL);
Parse the XPath expression.
exp = XmlXPathParse (xptproc, xpathexpr, &err);
Evaluate the XPath expression.
obj = XmlXPathEval(xptproc, exp, &err);
Delete the objects.
XmlXPathDestroyCtx (xptproc); XmlDestroy(xctx);
You can call the C Oracle XSLT processor as an executable by invoking bin/xsl:
xsl [switches] stylesheet instance or xsl -f [switches] [document filespec]
If no style sheet is provided, no output is generated. If there is a style sheet, but no output file, output goes to stdout
.
Table 17-1 lists the command line options.
Table 17-1 XSLT Processor for C: Command Line Options
Option | Description |
---|---|
-B BaseUri
|
Set the Base URI for XSLT processor: |
-e encoding
|
Specify default input file encoding ( |
-E encoding
|
Specify DOM or SAX encoding. |
-f |
File - interpret as filespec, not URI. |
-G xptrexprs
|
Evaluates XPointer schema examples given in a file. |
-h |
Help - show this usage. (Use |
-hh |
Show complete options list. |
-i n
|
Number of times to iterate the XSLT processing. |
-l language
|
Language for error reporting. |
-o XSLoutfile
|
Specifies output file of XSLT processor. |
-v |
Version - display parser version then exit. |
-V var value
|
Test top-level variables in C XSLT. |
-w |
Whitespace - preserve all whitespace. |
-W |
Warning - stop parsing after a warning. |
Oracle XSLT processor for C is part of the standard installation of Oracle Database.
See Also:
|
$ORACLE_HOME/xdk/demo/c/parser/
directory contains several XML applications to illustrate how to use the XSLT for C.
Table 17-2 lists the files in that directory:
Table 17-2 XSLT for C Demo Files
Sample File Name | Description |
---|---|
|
Source for XSLSample program |
|
Expected output from XSLSample |
|
XML file that can be used with XSLSample |
i |
Stylesheet that can be used with XSLSample |
|
XML version of Shakespeare's play |
|
Sample usage of XSLT Virtual Machine and compiler. It takes two filenames as input - XML file and XSLT stylesheet file. |
|
Sample usage of XSLT Virtual Machine and compiler. It takes XML file name and |
|
Sample usage of |
Change directories to the demo directory and read the README file. This will explain how to build the sample programs according to your operating system.
Here is the usage of XSLT processor sample XSLSample
, which takes two files as input, the XML file and the XSLT stylesheet:
XSLSample xmlfile xslss
A list of access control entries that determines which principals have access to a given resource or resources.
A server designed to host applications and their environments, permitting server applications to run. A typical example is Oracle Application Server, which is able to host Java, C, C++, and PL/SQL applications in cases where a remote client controls the interface.
A property of an element that consists of a name and a value separated by an equals sign and contained within the start-tags after the element name. In this example, <Price units='USD'>5</Price>
, units is the attribute and USD is its value, which must be in single or double quotes. Attributes may reside in the document or DTD. Elements may have many attributes but their retrieval order is not defined.
A term describing the communication between businesses in the selling of goods and services to each other. The software infrastructure to enable this is referred to as an exchange.
A term describing the communication between businesses and consumers in the selling of goods and services.
A programmatic technique in which one process starts another and then continues. The second process then calls the first as a result of an action, value, or other event. This technique is used in most programs that have a user interface to allow continuous interaction.
A stored program in Java or PL/SQL that adds the necessary functionality for the database to understand and manipulate a new datatype. Cartridges interface through the Extensibility Framework within Oracle Database version 8 or later. Oracle Text is such a cartridge, adding support for reading, writing, and searching text documents stored within the database.
Text in a document that should not be parsed is put within a CDATA
section. This allows for the inclusion of characters that would otherwise have special functions, such as &, <, >, and so on. CDATA
sections can be used in the content of an element or in attributes.
child element
An element that is wholly contained within another, which is referred to as its parent element. For example <Parent><Child></Child></Parent>
illustrates a child element nested within its parent element.
A utility that accepts an input file and creates a set of output classes that have corresponding functionality. In the case of the XML class generator, the input file is a DTD and the output is a series of classes that can be used to create XML documents conforming with the DTD.
The operating system environmental variable that the JVM uses to find the classes it needs to run applications.
Common Object Request Broker API (CORBA)
An Object Management Group standard for communicating between distributed objects across a network. These self-contained software modules can be used by applications running on different platforms or operating systems. CORBA objects and their data formats and functions are defined in the Interface Definition Language (IDL), which can be compiled in a variety of languages including Java, C, C++, Smalltalk and COBOL.
Common Oracle Runtime Environment (CORE)
The library of functions written in C that provides developers the ability to create code that can be easily ported to virtually any platform and operating system.
Database Access Descriptor (DAD)
A DAD is a named set of configuration values used for database access. A DAD specifies information such as the database name or the Oracle Net service name, the ORACLE_HOME
directory, and Globalization Support configuration information such as language, sort type, and date language.
A text fragment, which may be in XML format, that is returned to the requester embedded in an HTML page from a SQL query processed by the XSQL Servlet.
The datatype used for storing instances of the datatype that permits XPath-based navigation of database schemas.
The term used as the tag name designating the DTD or its reference within an XML document. For example, <!DOCTYPE person SYSTEM "person.dtd">
declares the root element name as person and an external DTD as person.dtd in the file system. Internal DTDs are declared within the DOCTYPE declaration.
Oracle XML DB uses the Document Location Hint to determine which XML schemas are relevant to processing the instance document. It assumes that the Document Location Hint will map directly to the URL used when registering the XML schema with the database. When the XML schema includes elements defined in multiple namespaces, an entry must occur in the schemaLocation
attribute for each of the XML schemas. Each entry consists of the namespace declaration and the Document Location Hint. The entries are separated from each other by one or more whitespace characters. If the primary XML schema does not declare a target namespace, then the instance document also must include a noNamespaceSchemaLocation
attribute that provides the Document Location Hint for the primary XML schema.
An in-memory tree-based object representation of an XML document that enables programmatic access to its elements and attributes. The DOM object and its interface is a W3C recommendation. It specifies the Document Object Model of an XML Document including the APIs for programmatic access. DOM views the parsed document as a tree of objects.
Document Type Definition (DTD)
A set of rules that define the legal structure of an XML document. DTDs are text files that derive their format from SGML and can either be included in an XML document by using the DOCTYPE element or by using an external file through a DOCTYPE reference.
To assure the integrity and accuracy of this data, for example, when regenerating XML documents stored in Oracle XML DB, Oracle XML DB uses a data integrity mechanism, called DOM fidelity. DOM fidelity refers to when the returned XML documents are identical to the original XML document, particularly for purposes of DOM traversals. Oracle XML DB assures DOM fidelity by using a binary attribute, SYS_XDBPD$
.
The basic logical unit of an XML document that can serve as a container for other elements such as children, data, and attributes and their values. Elements are identified by start-tags, such as <name>
, and end-tags, such as </name>
, or in the case of empty elements, <name/>
.
An element without text content or child elements. It can only contain attributes and their values. Empty elements are of the form <name/>
or <name></name>
, where there is no space between the tags.
An independent program module that runs within a JVM on the server. CORBA provides the infrastructure for EJBs, and a container layer provides security, transaction support, and other common functions on any supported server.
A string of characters that may represent either another string of characters or special characters that are not part of the document character set. Entities and the text that is substituted for them by the parser are declared in the DTD.
eXtensible Markup Language (XML)
An open standard for describing data developed by the World Wide Web Consortium (W3C) using a subset of the SGML syntax and designed for Internet use.
eXtensible Stylesheet Language (XSL)
The language used within stylesheets to transform or render XML documents. There are two W3C recommendations covering XSL stylesheets—XSL Transformations (XSLT) and XSL Formatting Objects (XSLFO).
XSL consists of two W3C recommendations: XSL Transformations for transforming one XML document into another and XSL Formatting Objects for specifying the presentation of an XML document. XSL is a language for expressing stylesheets. It consists of two parts:
A language for transforming XML documents (XSLT), and
An XML vocabulary for specifying formatting semantics (XSLFO).
An XSL stylesheet specifies the presentation of a class of XML documents by describing how an instance of the class is transformed into an XML document that uses the formatting vocabulary.
eXtensible Stylesheet Language Formatting Object (XSLFO)
The W3C standard specification that defines an XML vocabulary for specifying formatting semantics. See FOP.
eXtensible Stylesheet Language Transformation (XSLT)
Also written as XSL-T. The XSL W3C standard specification that defines a transformation language to convert one XML document into another.
Print formatter driven by XSL formatting objects. It is a Java application that reads a formatting object tree and then renders the resulting pages to a specified output. Output formats currently supported are PDF, PCL, PS, SVG, XML (area tree representation), Print, AWT, MIF and TXT. The primary output target is PDF.
The SQL operator that is part of Oracle Text and used for querying XMLType
datatypes for the existence of a specific XPath.
The data relating a folder to its children is managed by the Oracle XML DB hierarchical index, which provides a fast mechanism for evaluating path names similar to the directory mechanisms used by operating system filesystems. Any path name-based access will normally use the Oracle XML DB hierarchical index.
The datatype used for storing instances of the datatype that permits XPath-based navigation of database schemas in remote databases.
XML Information Set, an abstract data set consisting of a number of information items. It has at least one information item: the document node, but the infoset is not necessarily valid XML. The W3C Recommendation is at http://www.w3.org/TR/xml-infoset/
The SQL operator that is part of Oracle Text and is used for querying XMLType datatypes for searching for specific text within a specific XPath.
An XML document validated against an XML schema. If the instance document conforms to the rules of the schema, then it is said to be valid.
A term used in object-based languages such as Java and C++ to refer to the creation of an object of a specific class.
Integrated Development Environment (IDE)
A set of programs designed to aid in the development of software run from a single user interface. JDeveloper is an IDE for Java development, because it includes an editor, compiler, debugger, syntax checker, help system, and so on, to permit Java software development through a single user interface.
The collection of complex datatypes and their access in Oracle. These include text, video, time-series, and spatial data.
Internet Inter-ORB Protocol (IIOP)
The protocol used by CORBA to exchange messages on a TCP/IP network such as the Internet.
A high-level programming language developed and maintained by Sun Microsystems where applications run in a virtual machine known as a JVM. The JVM is responsible for all interfaces to the operating system. This architecture permits developers to create Java applications that can run on any operating system or platform that has a JVM.
Java 2 Platform, Enterprise Edition (J2EE)
The Java platform (Sun Microsystems) that defines multitier enterprise computing.
Java API for XML Processing (JAXP)
Enables applications to parse and transform XML documents using an API that is independent of a particular XML processor implementation.
Java Architecture for XML Binding (JAXB)
API and tools that map to and from XML documents and Java objects. A JSR-31 recommendation.
An independent program module that runs within a JVM, typically for creating user interfaces on the client. Also known as Java Bean. The server equivalent is called an Enterprise JavaBean (EJB). See also Enterprise JavaBean.
Java Database Connectivity (JDBC)
The programming API that enables Java applications to access a database through the SQL language. JDBC drivers are written in Java for platform independence but are specific to each database.
The collection of Java classes, runtime, compiler, debugger, and usually source code for a version of Java that makes up a Java development environment. JDKs are designated by versions, and Java 2 is used to designate versions from 1.2 onward.
Java Naming and Directory Interface (JNDI)
A programming interface from Sun for connecting Java programs to naming and directory services such as DNS, LDAP, and NDS. Oracle XML DB Resource API for Java/JNDI supports JNDI.
Java Runtime Environment (JRE)
The collection of complied classes that make up the Java virtual machine on a platform. JREs are designated by versions, and Java 2 is used to designate versions from 1.2 onward.
An extension to the servlet functionality that enables a simple programmatic interface to Web pages. JSPs are HTML pages with special tags and embedded Java code that is executed on the Web server or application server providing dynamic functionality to HTML pages. JSPs are actually compiled into servlets when first requested and run in the JVM of the server.
Java Specification Request (JSR)
A recommendation of the Java Community Process organization (JCP), such as JAXB.
The Java interpreter that converts the compiled Java bytecode into the machine language of the platform and runs it. JVMs can run on a client, in a browser, in a middle tier, on an intranet, on an application server, or in a database server.
Oracle Java IDE that enables application, applet, and servlet development and includes an editor, compiler, debugger, syntax checker, help system, an integrated UML class modeler, and so on. JDeveloper has been enhanced to support XML-based development by including the Oracle Java XDK components, integrated for use along with XML support, in its editor.
A mechanism used by Oracle XML DB to only convert the XML data for Java when the Java application first asks for it. This saves typical type conversion bottlenecks with JDBC.
marshalling
The process of traversing a Java content tree and writing an XML document that reflects the content of the tree. It is the inverse of unmarshalling.
Oracle XML DB provides for name-level locking rather than collection-level locking. When a name is added to a collection, an exclusive write lock is not placed on the collection, only that name within the collection is locked. The name modification is put on a queue, and the collection is locked and modified only at commit time.
notation attribute declaration
In XML, the declaration of a content type that is not part of those understood by the parser. These types include audio, video, and other multimedia.
Software that manages message communication between requesting programs on clients and between objects on servers. ORBs pass the action request and its parameters to the object and return the results back. Common implementations are JCORB and EJBs. See also CORBA.
Oracle Application Server
The Oracle Application Server product integrates all the core services and features required for building, deploying, and managing high-performance, n-tier, transaction-oriented Web applications within an open standards framework.
The operating system environment variable that identifies the location of the Oracle database installation for use by applications.
The Oracle file system and Java-based development environment that either runs inside the database or on a middle tier and provides a means of creating, storing, and managing multiple types of documents in a single database repository.
Oracle XML Developer's Kit (XDK)
The set of libraries, components, and utilities that provide software developers with the standards-based functionality to XML-enable their applications. In the case of the Oracle Java components of XDK, the kit contains an XML parser, an XSLT processor, the XML class generator, the JavaBeans, and the XSQL Servlet.
Ordered Collection in Tables (OCT)
When elements of a VARRAY
are stored in a separate table, they are referred to as an Ordered Collection in Tables.
An Oracle tool that provides full-text indexing of documents and the capability to do SQL queries over documents, along with XPath-like searching.
A high-performance XML storage and retrieval technology provided with Oracle database server. It is based on the W3C XML data model.
Organization for the Advancement of Structured Information (OASIS)
An organization of members chartered with promoting public information standards through conferences, seminars, exhibits, and other educational events. XML is a standard that OASIS is actively promoting as it is doing with SGML.
An element that surrounds another element, which is referred to as its child element. For example, <Parent><Child></Child></Parent>
illustrates a parent element wrapping its child element.
Parsed Character Data (PCDATA)
The element content consisting of text that should be parsed but is not part of a tag or nonparsed data.
The name of a resource that reflects its location in the repository hierarchy. A path name is composed of a root element (the first /), element separators (/) and various sub-elements (or path elements). A path element may be composed of any character in the database character set except ("\", "/" ). These characters have a special meaning for Oracle XML DB. Forward slash is the default name separator in a path name and backward slash may be used to escape characters.
An entity that may be granted access control privileges to an Oracle XML DB resource. Oracle XML DB supports as principals:
Database users.
Database roles. A database role can be understood as a group, for example, the DBA role represents the DBA group of all the users granted the DBA role.
Users and roles imported from an LDAP server are also supported as a part of the database general authentication model.
The opening part of an XML document containing the XML declaration and any DTD or other declarations needed to process the document.
The set of database objects, in any schema, that are mapped to path names. There is one root to the repository ("/") which contains a set of resources, each with a path name.
The name of a resource within its parent folder. Resource names must be unique (potentially subject to case-insensitivity) within a folder. Resource names are always in the UTF-8 character set (NVARCHAR2
).
The element that encloses all the other elements in an XML document and is between the optional prolog and epilog. An XML document is only permitted to have one root element.
The definition of the structure and data types within a database. It can also be used to refer to an XML document that support the XML Schema W3C recommendation.
The process used to modify XML schemas that are registered with Oracle XML DB. Oracle XML DB provides the PL/SQL procedure DBMS_XMLSCHEMA.CopyEvolve()
. This copies existing XML instance documents to temporary tables, drops and re-registers the XML schema with Oracle XML DB, and copies the XML instance documents to the new XMLType
tables.
The primary security protocol on the Internet; it utilizes a public key /private key form of encryption between browsers and servers.
The HTML command used to place data or other content into a Web page before sending it to the requesting browser.
A Java application that runs in a server, typically a Web or application server, and performs processing on that server. Servlets are the Java equivalent to CGI scripts.
Simple Object Access Protocol (SOAP)
An XML-based protocol for exchanging information in a decentralized, distributed environment.
An ANSI specification for representing XML in SQL. Oracle SQL includes SQL/XML functions that query XML. The specification is not yet completed.
Structured Generalized Markup Language (SGML)
An ISO standard for defining the format of a text document implemented using markup and DTDs.
Structured Query Language (SQL)
The standard language used to access and process data in a relational database.
In XML, the term used to describe an XML document that consists of XSL processing instructions used by an XSLT processor to transform or format an input XML document into an output one.
The native SQL function that returns as a single XML document the results of a passed-in SYS_XMLGEN
SQL query. This can also be used to instantiate an XMLType
.
The native SQL function that returns as an XML document the results of a passed-in SQL query. This can also be used to instantiate an XMLType
.
A single piece of XML markup that delimits the start or end of an element. Tags start with <
and end with >
. In XML, there are start-tags (<name>
), end-tags (</name>
), and empty tags (<name/>
).
TransX Utility is a Java API that simplifies the loading of translated seed data and messages into a database.
Uniform Resource Locator (URL)
The address that defines the location and route to a file on the Internet. URLs are used by browsers to navigate the World Wide Web and consist of a protocol prefix, port number, domain name, directory and subdirectory names, and the file name. For example, http://www.oracle.com:80/technology/tech/xml/index.htm
specifies the location and path a browser will travel to find the OTN XML site on the World Wide Web.
Universal Description, Discovery and Integration (UDDI)
This specification provides a platform-independent framework using XML to describe services, discover businesses, and integrate business services on the Internet.
unmarshalling
The process of reading an XML document and constructing a tree of Java content objects. Each content object corresponds directly to an instance in the input document of the corresponding schema component.
See Also: marshalling
The term used to refer to an XML document when its structure and element content is consistent with that declared in its associated DTD or XML schema.
The cartridge within Oracle Application Server that processes URLs and sends them to the appropriate cartridge.
Web Services Description Language (WSDL)
A general purpose XML language for describing the interface, protocol bindings, and deployment details of Web services.
The term used to refer to an XML document that conforms to the syntax of the XML version declared in its XML declaration. This includes having a single root element, properly nested tags, and so forth.
The committee within the W3C that is made up of industry members that implement the recommendation process in specific Internet technology areas.
World Wide Web Consortium (W3C)
An international industry consortium started in 1994 to develop standards for the World Wide Web. It is located at http://www.w3c.org
.
World Wide Web Distributed Authoring and Versioning (WebDAV)
The Internet Engineering Task Force (IETF) standard for collaborative authoring on the Web. Oracle XML DB Foldering and Security features are WebDAV-compliant.
An XML element defined by the Oracle XML DB schema that contains binary data. XDBbinary elements are stored in the repository when completely unstructured binary data is uploaded into Oracle XML DB.
The XML Linking language consisting of the rules governing the use of hyperlinks in XML documents. These rules are being developed by the XML Linking Group under the W3C recommendation process. This is one of the three languages XML supports to manage document presentation and hyperlinks (XLink, XPointer, and XPath).
A W3C recommendation that describes the use of the xml:base
attribute, which can be inserted in an XML document to specify a base URI
other than the base URI of the document or external entity. The URI
s in the document are resolved by means of the given base.
A set of services that allows for integration with the Oracle E-Business Suite to create and consume XML messages triggered by business events.
The term to describe a set of related element names or attributes within an XML document. The namespace syntax and its usage is defined by a W3C Recommendation. For example, the <xsl:apply-templates/ >
element is identified as part of the XSL namespace. Namespaces are declared in the XML document or DTD before they are used, with the following attribute syntax: xmlns:xsl="http://www.w3.org/TR/WD-xsl".
In XML, a software program that receives an XML document and determines whether it is well-formed and, optionally, valid. The Oracle XML parser supports both SAX and DOM interfaces.
XML Pipeline Definition Language
W3C recommendation that enables you to describe the processing relations between XML resources.
XML processor
A software program that reads an XML document and processes it, that is, performs actions on the document based on a set of rules. Validity checkers and XML editors are examples of processors.
The on-going effort of the W3C to create a standard for the language and syntax to query XML documents.
The XML Schema language, also called simply "XML Schema," is a W3C standard for the use of simple data types and complex structures within an XML document. It addresses areas currently lacking in DTDs, including the definition and validation of data types.
Oracle XML Schema processor automatically ensures validity of XML documents and data used in e-business applications, including online exchanges. It adds simple and complex datatypes to XML documents and replaces DTD functionality with an XML schema definition XML document.
Allows Oracle XML DB protocol servers to recognize that an XML document inserted into Oracle XML DB repository is an instance of a registered XML schema. This means that the content of the instance document is automatically stored in the default table defined by that XML schema. Defined by the W3C XML Schema working group and based on adding attributes that identify the target XML schema to the root element of the instance document. These attributes are defined by the XMLSchema-instance namespace.
Used to identify an instance document as a member of the class defined by a particular XML schema. You must declare the XMLSchema-instance namespace by adding a namespace declaration to the root element of the instance document. For example: xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
.
When using Oracle XML DB, you must first register your XML schema. You can then use the XML schema URLs while creating XMLType
tables, columns, and views.
This Oracle utility can generate an XML document (string or DOM) given a SQL query or a JDBC ResultSet
object. XSU can also extract the data from an XML document, then insert, update, or delete rows in a database table.
XMLType
XMLType
is an Oracle datatype that stores XML data using an underlying CLOB
column, or object-relational columns, or a binary format within a table or view.
Oracle XML DB provides a way to wrap existing relational and object-relational data in XML format. This is especially useful if, for example, your legacy data is not in XML but you have to migrate it to an XML format.
The open standard syntax for addressing elements within a document used by XSL and XPointer. XPath is currently a W3C recommendation. It specifies the data model and grammar for navigating an XML document utilized by XSLT, XLink and XML Query.
Can be used when the XMLType
is stored in structured storage (object-relational) using an XML schema. Queries using XPath can potentially be rewritten directly to underlying object-relational columns. XPath query rewrite is used for XPaths in SQL functions such as existsNode()
, extract()
, extractValue()
, and updateXML()
. It enables the XPath to be evaluated against the XML document without constructing the XML document in memory.
The term and W3C recommendation to describe a reference to an XML document fragment. An XPointer can be used at the end of an XPath-formatted URI. It specifies the identification of individual entities or fragments within an XML document using XPath navigation.
Oracle's XSLT Virtual Machine is the software implementation of a "CPU" designed to run compiled XSLT code. The concept of virtual machine assumes a compiler compiling XSLT stylesheets to a program of byte-codes, or machine instructions for the "XSLT CPU".
A Java-based servlet that can dynamically generate XML documents from one or more SQL queries and optionally transform the documents in the server with an XSLT stylesheet.
This chapter contains these topics:
Note: Use the new unified C++ API inxml.hpp for new XDK applications. The old C++ API in oraxml.hpp is deprecated and supported only for backward compatibility, but will not be enhanced. It will be removed in a future release. |
The XML Schema processor for C++ is a companion component to the XML parser for C++ that allows support to simple and complex datatypes into XML applications.
The XML Schema processor for C++ supports the W3C XML Schema Recommendation. This makes writing custom applications that process XML documents straightforward, and means that a standards-compliant XML Schema processor is part of the XDK on each operating system where Oracle is ported.
XML Schema processor for C++ has the following features:
Supports simple and complex types
Built upon the XML parser for C++
Supports the W3C XML Schema Recommendation
The XML Schema processor for C++ class is OracleXml::Parser::SchemaValidator
.
Interface SchemaValidator
is an abstract template class to handle XML schema-based validation of XML documents.
The XML Schema processor for C++ can be called as an executable by invoking bin/schema
in the install area. This takes the arguments:
XML instance document
Optionally, a default schema
Optionally, the working directory
Table 27-1 lists the options (can be listed if the option is invalid or -h is the option):
Table 27-1 XML Schema Processor for C++ Command Line Options
Option | Description |
---|---|
|
Always exit with code 0 (success). |
|
Specify default input file encoding. |
|
Specify output/data/presentation encoding. |
|
Help. Prints these choices. |
|
Ignore provided schema. |
|
Validation option. |
|
Print document instance to |
|
Force the Unicode path. |
|
Version - display version, then exit. |
The XML Schema processor for C++ can also be invoked by writing code using the supplied APIs. The code must be compiled using the headers in the include
subdirectory and linked against the libraries in the lib
subdirectory. See Makefile
or Make.bat
in the xdk/demo/cpp/schema
directory for details on how to build your program.
Error message files in different languages are provided in the mesg
subdirectory.
The directory xdk/demo/cpp/schema
contains a sample application that illustrates how to use Oracle XML Schema processor for C++ with its API. Table 27-2 lists the sample files provided.
Table 27-2 XML Schema Processor for C++ Samples Provided
Sample File | Description |
---|---|
|
Makefile to build the sample programs and run them, verifying correct output. |
|
Trivial program which invokes the XML Schema for C++ API |
|
Sample schema, instance document, expected output respectively, after running |
|
Second sample schema's, instance document, expected output respectively, after running |
|
Third sample schema's, instance document, expected output respectively, after running |
To build the sample programs, run make
.
To build the programs and run them, comparing the actual output to expected output:
make sure
This Preface contains these topics:
Oracle XML Developer's Kit Programmer's Guide is intended for application developers interested in learning how the various language components of the Oracle XML Developer's Kit (XDK) can work together to generate and store XML data in a database or in a document outside the database. Examples and sample applications are introduced where possible.
To use this document, you need familiarity with XML and a third-generation programming language such as Java, C, or C++.
For information about Oracle's commitment to accessibility, visit the Oracle Accessibility Program website at http://www.oracle.com/pls/topic/lookup?ctx=acc&id=docacc
.
Access to Oracle Support
Oracle customers have access to electronic support through My Oracle Support. For information, visit http://www.oracle.com/pls/topic/lookup?ctx=acc&id=info
or visit http://www.oracle.com/pls/topic/lookup?ctx=acc&id=trs
if you are hearing impaired.
For more information, see these Oracle resources:
Many of the examples in this documentation are provided with your software in the following directories:
$ORACLE_HOME/xdk/demo/java/
$ORACLE_HOME/xdk/demo/c/
$ORACLE_HOME/xdk/java/sample/
$ORACLE_HOME/rdbms/demo
Many of the examples in this book use the sample schemas, which are installed by default when you select the Basic Installation option with an Oracle Database installation. Refer to Oracle Database Sample Schemas for information on how these schemas were created and how you can use them yourself.
For additional information about XML, see:
Oracle Database 10g XML & SQL: Design, Build, & Manage XML Applications in Java, C, C++, & PL/SQL by Mark Scardina, Ben Chang, and Jinyu Wang, Oracle Press, http://www.osborne.com/oracle/
WROX publications, especially XML Design and Implementation by Paul Spencer, which covers XML, XSL, and development.
Building Oracle XML Applications by Steve Muench, O'Reilly, http://www.oreilly.com/catalog/orxmlapp/
The XML Bible, http://www.ibiblio.org/xml/books/biblegold/
XML, Java, and the Future of the Web by Jon Bosak, Sun Microsystems, http://www.ibiblio.org/bosak/xml/why/xmlapps.htm
XML for the Absolute Beginner by Mark Johnson, JavaWorld, http://www.javaworld.com/jw-04-1999/jw-04-xml_p.html
XML And Databases by Ronald Bourret, http://www.rpbourret.com/xml/XMLAndDatabases.htm
XML Specifications by the World Wide Web Consortium (W3C), http://www.w3.org/XML/
XML.com
, a broad collection of XML resources and commentary, http://www.xml.com/
Annotated XML Specification by Tim Bray, XML.com
, http://www.xml.com/axml/testaxml.htm
XML.org
, hosted by OASIS as a resource to developers of purpose-built XML languages, http://xml.org/
The following text conventions are used in this document:
Convention | Meaning |
---|---|
boldface | Boldface type indicates graphical user interface elements associated with an action, or terms defined in text or the glossary. |
italic | Italic type indicates book titles, emphasis, or placeholder variables for which you supply particular values. |
monospace | Monospace type indicates commands within a paragraph, URLs, code in examples, text that appears on the screen, or text that you enter. |
This appendix lists TXU error messages that may be encountered in applications that use Oracle XDK for Java.
These error messages may occur during the execution of TXU interfaces.
These error messages are in the range TXU-0100 through TXU-0199.
Cause: There is not a placeholder for the parameter in the query
Action: Supply a parameter whose id can be found as an associated placeholder in the associated query
Cause: Attributes 'col' and 'constant' cannot coexist
Action: Remove either 'col' or 'constant' attribute
Cause: The document lacks an expected node
Action: Supply the missing node
Cause: The element lacks a required attribute of 'col' or 'constant'
Action: Supply either 'col' or 'constant' attribute
Cause: An error occurred during the SQL execution
Action: Resolve the error in the SQL statement
Cause: The SQL query returned no data
Action: Supply data or modify your query
Cause: An attempt to process an unsupported datatype was made
Action: Change the datatype to a supported one
Cause: The size-unit attribute is specified but maxsize is not.
Action: Supply the maxsize attribute, too
Cause: The length of the text data is too long
Action: Shorten the data so it fits in the limit, or enlarge the maxsize attribute and ensure the database column is large enough
Cause: A column in the data section is not declared in the columns section
Action: Modify the column name to a declared one
Cause: A column is declared but the data is missing.
Action: Supply the col element whose name attribute matches the column name
Cause: The query parameter refers to an undeclared column
Action: Specify a declared column
Cause: A column with a query cannot have the specified attribute
Action: Remove either the attribute or query
Cause: The format is in error as reported
Action: Correct the erroneous part
These error messages are in the range TXU-0300 through TXU-0399.
Cause: The document could not be located
Action: Modify the document location or supply the document at the location
Cause: An I/O error happened when reading the file
Action: Resolve the I/O problem
Cause: The archive file could not be located
Action: Ensure that the CLASSPATH includes TransX correctly and only once
Cause: The schema definition of DLF could not be located
Action: Obtain an unbroken copy of a TransX archive
Cause: The path for the archive could not be determined
Action: Ensure that the CLASSPATH includes TransX correctly and only once
Cause: The operation was attempted without a database connection
Action: Open a connection first
Cause: The table name is not provided
Action: Specify a table name
Cause: The data dictionary is corrupted
Action: Restore the data dictionary
Cause: The file name is invalid
Action: Supply a good file name
These error messages are in the range TXU-0400 through TXU-0499.
Cause: An internal assertion was not successful
Action: Contact Oracle customer support
Cause: An internal assertion was not successful
Action: Contact Oracle customer support
Cause: An internal assertion was not successful
Action: Contact Oracle customer support
Cause: An internal assertion was not successful
Action: Contact Oracle customer support
This chapter contains these topics:
TransX Utility enables you to transfer XML to a database. More specifically, the TransX utility is an application of XML SQL Utility (XSU) that loads translated seed data and messages into a database schema. If you have data to be populated into a database in multiple languages, then the utility provides the functionality that you would otherwise need to develop with XSU.
The TransX utility is particularly useful when handling multilingual XML. The utility does the following:
Automatically manages the change variables, start sequences, and additional SQL statements that would otherwise require multiple inserts or sessions. Thus, translation vendors do not need to work with unfamiliar SQL and PL/SQL scripts.
Automates character encoding. Consequently, loading errors due to incorrect encoding are impossible so long as the data file conforms to the XML standard.
Reduces globalization costs by preparing strings to be translated, translating the strings, and loading them into the database.
Minimizes translation data format errors and accurately loads the translation contents into pre-determined locations in the database. When the data is in a predefined format, the TransX utility validates it.
Eliminates syntax errors due to varying Globalization Support settings.
Does not require the UNISTR
construct for every piece of NCHAR
data.
This chapter assumes that you are familiar with XML SQL Utility (XSU) because TransX is an application of XSU.
This section describes the following features of the TransX utility:
When inserting multilingual data or data translations into an Oracle database, or when encoding, each XML file requires validation. The traditional translation data loading method is to change the NLS_LANG
environment variable setting when switching load files. This variable sets the language and territory used by the client application and the database server. It also sets the client character set, which is the character set for data entered or displayed by a client program.
In the traditional method, each load file is encoded in a character set suitable for its language, which is necessary because translations must be performed in the same file format—typically in a SQL script—as the original. The NLS_LANG
setting changes as files are loaded to adapt to the character set that corresponds to the language. As well as consuming time, this approach is error-prone because the encoding metadata is separate from the data itself.
With the TransX utility you use an XML document with a predefined format called a dataset. The dataset contains the encoding information and the data so that you can transfer multilingual data without changing NLS_LANG
settings. The TransX utility frees development and translation groups by maintaining the correct character set while loading XML data into the database.
See Also: Oracle Database Globalization Support Guide to learn about theNLS_LANG environment variable |
The TransX utility provides a command-line interface and programmable API. The utility complies with a data format defined to be the canonical method for the representation of seed data loaded into the database. The format is intuitive and simplified for use by translation groups. The format specification defines how translators can describe the data so that it is loaded in an expected way. You can represent the values in the data set with scalar values or expressions such as constants, sequences, and queries.
Table 12-1 describes other useful TransX utility features.
Table 12-1 TransX Utility Features
Feature | TransX Utility . . . |
---|---|
Command-line interface |
Provides easy-to-use commands. |
User API |
Exposes a Java API. |
Validation |
Validates the data format and reports errors. |
Whitespace handling |
Does not consider whitespace characters in the data set as significant unless otherwise specified in various granularity. |
Unloading |
Exports the result into the standard data format based on an input query. |
Intimacy with translation exchange format |
Enables transformation to and from translation exchange format. |
Localized user interface |
Provides messages in many languages. |
This section contains the following topics:
TransX is accessible through the following API:
oracle.xml.transx.loader
class, which contains the getLoader()
method to obtain a TransX instance
oracle.xml.transx.TransX
interface, which is the TransX API
Figure 12-1 illustrates the basic process for using the TransX API to transfer XML to an Oracle database.
Figure 12-1 Basic Process of a TransX Application
The basic process of a TransX application is as follows:
Create a TransX loader object. Instantiate the TransX
class by calling getLoader()
as follows:
TransX transx = loader.getLoader();
Start a data loading session by supplying database connection information with TransX.open()
. You create a session by supplying the JDBC connect string, database username, and database password. You have the following options:
Create the connection with the JDBC OCI driver. The following code fragment illustrates this technique and connects with the supplied user name and password:
transx.open( "jdbc:oracle:oci8:@", user, passwd );
Create the connection with the JDBC thin driver. The thin driver is written in pure Java and can be called from any Java program. The following code fragment illustrates this technique and connects:
transx.open( "jdbc:oracle:thin:@//myhost:1521/myservicename", user,passwd);
The thin driver requires the host name (myhost
), port number (1521
), and the service name (myservicename
). The database must have an active TCP/IP listener.
Note: If you are just validating your data format, then you do not need to establish a database connection because the validation is performed by TransX. Thus, you can invoke theTransX.validate() method without a preceding open() call. |
Configure the TransX loader. Table 12-2 describes configuration methods.
Table 12-2 TransX Configuration Methods
Method | Description |
---|---|
|
Sets the operation mode on duplicates. The mode determines TransX behavior when there are one or more existing rows in the database whose values in the key columns are the same as those in the dataset to be loaded. You can specify the constants |
|
Sets the case of language tag. By default the loader uses the style specified in the |
|
Specifies how the loader should handle whitespace. The default is |
|
Sets the validation mode. The default is |
The following example specifies that the loader should skip duplicate rows and not validate the dataset:
transx.setLoadingMode( LoadingMode.SKIP_DUPLICATES ); transx.setValidationMode( false );
Load the datasets by invoking TransX.load()
. The same JDBC connection is used during the iteration of the load operations. For example, load three datasets as follows:
String datasrc[] = {"data1.xml", "data2.xml", "data3.xml"}; ... for ( int i = 0 ; i < datasrc.length ; i++ ) { transx.load( datasrc[i] ); }
Close the loading session by invoking TransX.close()
. This method call closes the database connection:
transx.close();
See Also:
|
Demo programs for the TransX utility are included in $ORACLE_HOME/xdk/demo/java/transx
. Table 12-3 describes the XML files and programs that you can use to test the utility.
Table 12-3 TransX Utility Sample Files
File | Description |
---|---|
|
A text file that describes how to set up the TransX demos. |
|
A sample output file. The following command generates a file
transx -s "jdbc:oracle:thin:@//myhost:1521/myservicename" user
-pw emp.xml emp
The |
|
A SQL file that drops the tables and sequences created for the demo. |
|
A sample Java application that creates a JDBC connection and loads three datasets into the database. |
|
A SQL script that creates two tables and a sequence for use by the demo application. |
|
A sample dataset. |
Documentation for how to compile and run the sample programs is located in the README
. The basic steps are as follows:
Change into the $ORACLE_HOME/xdk/demo/java/transx
directory (UNIX) or %ORACLE_HOME%\xdk\demo\java\transx
directory (Windows).
Make sure that your environment variables are set as described in "Setting Up the Java XDK Environment". It is recommended that you set the $ORACLE_SID
(UNIX) or %ORACLE_SID%
(Windows) environment variables to the default database.
Note: For security purposes, do not expose passwords in command-line interfaces. If "-pw " is specified instead of the password in TransX , the user will be prompted for the password [ Enter password : ]. When the user types the password, it will not be echoed; instead, "* "s will be printed in the command window. |
Set up the sample database objects by executing txdemo1.sql
. Connect to the database and run the txdemo1.sql
script as follows:
@txdemo1
Run the TransX utility from the command line. For example, assume that you want to connect with the Java thin driver and that your host is myhost
, your port is 1521
, and your service name is myservicename
. Enter the user name where the token user
appears. You can execute the following command to load dataset txdemo1.xml
:
transx "jdbc:oracle:thin:@//myhost:1521/myservicename" user -pw txdemo1.xml
When the operation is successful, nothing is printed out on your terminal.
Query the database to determine whether the load was successful. For example:
SELECT * FROM i18n_messages;
Drop the demo objects to prepare for another test. Connect to the database and run the txclean.sql
script as follows:
@txclean
Compile the Java demo program. For example:
javac txdemo1.java
Run the Java program, using the same JDBC and database connection data that you used when invoking the command-line interface. For example:
java txdemo1 "jdbc:oracle:thin:@//myhost:1521/myservicename" user -pw\
txdemo1.xml
Perform the same query test (step 5) and clean-up operation (step 6) as before.
Run the TransX Utility to unload data into the predefined XML format. For example:
transx -s "jdbc:oracle:thin:@//myhost:1521/myservicename" user -pw emp.xml emp
Compare the data in emp.xml
with emp-dlf.xml
.
Note: For simplicity in demonstrating this feature, this example does not perform the password management techniques that a deployed system normally uses. In a production environment, follow the Oracle Database password management guidelines, and disable any sample accounts. See Oracle Database Security Guide for password management guidelines and other security recommendations. |
TransX utility is packaged with Oracle Database. By default, the Oracle Universal Installer installs the utility on disk. As explained in "Java XDK Component Dependencies", the TransX library is $ORACLE_HOME/lib/xml.jar
(UNIX) and %ORACLE_HOME%\lib\xml.jar
(Windows).
You can run the TransX utility from the operating system command line with the following syntax:
java oracle.xml.transx.loader
The XDK includes a script version of TransX named $ORACLE_HOME/bin/transx
(UNIX) and %ORACLE_HOME%\bin\transx.bat
(Windows). Assuming that your PATH
variable is set correctly, you can run TransX as follows:
transxoptions
parameters
transx.batoptions
parameters
For example, the following command shows valid syntax:
transx -s "jdbc:oracle:thin:@//myhost:1521/myservicename" user -pw emp.xml emp
Table 12-4 describes the options for the TransX utility.
Table 12-4 TransX utility Command-line Options
Option | Meaning | Description |
---|---|---|
|
Update existing rows. |
Does not skip existing rows but updates them. To exclude a column from the update operation, set the |
|
Raise exception if a row is already existing in the database. |
Throws an exception if a duplicate row is found. By default, TransX skips duplicate rows. Rows are considered duplicate if the values for lookup-key column(s) in the database and the data set are the same. |
|
Print data in the database in the predefined format. |
Similar to the |
|
Save data in the database into a file in the predefined format. |
Performs unloading. TransX Utility queries the database, formats the result into the predefined XML format, and stores it under the specified file name. |
|
Print the XML to load. |
Prints out the data set for insert in the canonical format of XSU. |
|
Print the XML for update. |
Prints out the data set for update in the canonical format of XSU. |
|
Omit validation (as the data set is parsed it is validated by default). |
Causes TransX Utility to skip the format validation, which is performed by default. |
|
Validate the data format and exit without loading. |
Causes TransX Utility to perform validation and exit. |
|
Preserve white space. |
Causes TransX Utility to treat whitespace characters (such as \t, \r, \n, and ' ') as significantAz. The utility condenses consecutive whitespace characters in string data elements into one space character by default. |
|
Set the case of language tag. |
Causes TransX Utility to override the style of normalizing the case of language tag specified in the |
Note the following command-line option exceptions:
-u
and -e
are mutually exclusive.
-v
must be the only option followed by data, as shown in the examples.
-x
must be the only option followed by connect information and a SQL query, as shown in the examples.
Omitting all arguments results in the display of the usage information shown in Table 12-4.
Table 12-5 describes the command-line parameters for the TransX utility.
Table 12-5 TransX utility Command-line Parameters
Parameter | Description |
---|---|
connect_string |
The JDBC connect string. See Oracle Database JDBC Developer's Guide, |
username |
Database user name. |
password |
Password for the database user, or " |
datasource |
An XML document specified by filename or URL. |
options |
Described in Table 12-4, "TransX utility Command-line Options". |
The TransX utility is especially useful for populating a database with multilingual data. To use the utility to transfer data in and out of a database schema you must create a dataset that maps to this schema. This section describes a typical use scenario in which you use TransX to organize translated application messages in a database.
This section contains the following topics:
To build an internationalized system, it is essential to decouple localizable resources from business logic. A typical example of such a resource is translated text information. Data that is specific to a particular region and shares a common language and cultural conventions must be organized with a resource management facility that can retrieve locale-specific information. A database is often used to store such data because of easy maintenance and flexibility.
Assume that you create the table with the structure and content shown in Example 12-1 and insert data.
Example 12-1 Structure of Table translated_messages
CREATE TABLE translated_messages ( MESSAGE_ID NUMBER(4) CONSTRAINT tm_mess_id_nn NOT NULL , LANGUAGE_ID VARCHAR2(42) , MESSAGE VARCHAR2(200) );
The column language_id
is defined in this table so that applications can retrieve messages based on the preferred language of the end user. It contains abbreviations of language names to identify the language of messages.
Example 12-2 shows sample data for the table.
Chapter 13, "Data Loading Format (DLF) Specification" describes the complete syntax of the Data Loading Format (DLF) language. This language is used to create a DLF document that provides the input to TransX.
Given the dataset (the input data) in the canonical format, the TransX utility loads the data into the designated locations in the database. Note that TransX does not create the database objects: you must create the tables or views before attempting to load data.
An XML document that represents the translated_messages
table created in Example 12-1 looks something like Example 12-3. The dataset reflects the structure of the target table, which in this case is called translated_messages
.
Example 12-3 example.xml
<?xml version="1.0"?> <table name="translated_messages"> <!-- Specify the unique identifier --> <lookup-key> <column name="message_id" /> <column name="language_id" /> </lookup-key> <!-- Specify the columns into which data will be inserted --> <columns> <column name="message_id" type="number"/> <column name="language_id" type="string" constant="us" translate="yes"/> <column name="message" type="string" translate="yes"/> </columns> <!-- Specify the data to be inserted --> <dataset> <row> <col name="message_id">1</col> <col name="message" translation-note="dnt'X'">Welcome to System X</col> </row> <row> <col name="message_id">2</col> <col name="message">Please enter username and password</col> </row> <!-- ... --> </dataset> </table>
The XML document in Example 12-3 starts with the following declaration:
<?xml version="1.0"?>
Its root element <table>
, which has an attribute that specifies the name of the table, encloses all the other elements:
<table name="translated_messages"> ... </table>
As explained in "Elements in DLF", the <table>
element contains three subsections:
The preceding sections map to elements in Example 12-3 as follows:
<lookup-key>...</lookup-key> <columns>...</columns> <dataset>...</dataset>
The lookup keys are columns used to evaluate rows if they already exist in the database. Because we want a pair of message and language IDs to identify a unique string, the document lists the corresponding columns. Thus, the message_id
, language_id
, and message
columns in table translated_messages
map to the attributes in the <column>
element as follows:
<column name="message_id" type="number"/> <column name="language_id" type="string" constant="us" translate="yes"/> <column name="message" type="string" translate="yes"/>
The columns section should mirror the table structure because it specifies which piece of data in the dataset section maps to which table column. The column names should be consistent throughout the XML dataset and database. You can use the <column>
attributes in Table 12-6 to describe the data to be loaded. Note that these attributes form a subset of the DLF attributes described in "Attributes in DLF".
Table 12-6 <column> Attributes
Attribute | Description | Example |
---|---|---|
type |
Specifies the datatype of a column in the dataset. This attribute specifies the kind of text contained in the |
<column name="col" type="string" /> |
constant |
Specifies a constant value. A column with a fixed value for each row does not have to repeat that same value. |
<column name="col" type="string" constant="us" /> |
language |
The language attribute indicates that the column is the language column, which stores a language tag. It works in the same way as the constant attribute, except for the role to declare the column is the language column. |
<column name="language" type="string" language="us" /> |
sequence |
Specifies a sequence in the database used to fill in the value for this column. |
<column name="id" type="number" sequence="id_sq" /> |
translate |
Indicates whether the text of this column or parameter is to be translated. |
<column name="msg" type="string" translate="yes"/> |
The constant
attribute of a <column>
element specifies a value to be stored into the corresponding column for every row in the dataset section. Because in this example we are working in the original language, the language_id
column is set to the value us
.
Defining the Language Column
Alternatively, the language_id
column may use the language
attribute instead of the constant
attribute. A DLF document with the language
attribute can use the lang
attribute in the xml namespace. A language column can use the "%x" placeholder to get its value from the standard xml:lang
attribute at the root table element.Thus translate="yes"
is not needed, because the value "%x" does not have to be translated. The result of loading this DLF is the same as Example 10-3.
Example 12-4 example.xml with a Language Attribute
<?xml version="1.0"?>
<table xml:lang="us" name="translated_messages">
<!-- Specify the unique identifier -->
<lookup-key>
<column name="message_id" />
<column name="language_id" />
</lookup-key>
<!-- Specify the columns into which data will be inserted -->
<columns>
<column name="message_id" type="number"/>
<column name="language_id" type="string" language="%x"/>
<column name="message" type="string" translate="yes"/>
</columns>
<!-- Specify the data to be inserted -->
<dataset>
<row>
<col name="message_id">1</col>
<col name="message" translation-note="dnt'X'">Welcome to System X</col>
</row>
<row>
<col name="message_id">2</col>
<col name="message">Please enter username and password</col>
</row>
<!-- ... -->
</dataset>
</table>
As explained in Table 13-10, the valid values for the type
attribute are string
, number
, date
, and dateTime
. These values correspond to the datatypes defined in the XML schema standard, so each piece of data should conform to the respective datatype definition. In particular, it is important to use the ISO 8601 format for the date
and dateTime
datatypes, as shown in Table 12-7.
Table 12-7 date and dateTime Formats
Datatype | Format | Example |
---|---|---|
date |
CCYY-MM-DD |
2009-05-20 |
dateTime |
CCYY-MM-DDThh:mm:ss |
2009-05-20T16:01:37 |
Example 12-5 shows how you can represent a table row with dateTime
data in a TransX dataset.
As explained in "Attributes in DLF", you can use the translation
attribute to specify whether the column contains translated data. In Example 12-3, two <column>
elements use the translate
attribute differently. The attribute for the language_id
column specifies that the value of the constant
attribute should be translated:
<column name="language_id" type="string" constant="us" translate="yes"/>
In contrast, the following translate
attribute requests translation of the data in the dataset section with a name that matches this column:
<column name="message" type="string" translate="yes"/>
For example, the preceding element specifies that the following messages in the dataset section should be translated:
<col name="message" translation-note="dnt'X'">Welcome to System X</col> <col name="message">Please enter username and password</col>
When translating messages for applications, you may decide that specified words or phrases should be left untranslated. The translation-note
attribute shown in the preceding example achieves this goal.
An XSLT processor can convert the preceding format into another format for exchanging translation data among localization service providers for use with XML-based translation tools. This transformation insulates developers from tasks such as keeping track of revisions, categorizing translatable strings into units, and so on.
Example 12-6 shows what the document in Example 12-3 looks like after translation.
Example 12-6 example_es.xml
<?xml version="1.0"?> <table xml:lang="es" name="translated_messages"> <!-- Specify the unique identifier --> <lookup-key> <column name="message_id" /> <column name="language_id" /> </lookup-key> <!-- Specify the columns into which data will be inserted --> <columns> <column name="message_id" type="number"/> <column name="language_id" type="string" constant="es" translate="yes"/>
Example 12-7 shows what the document in Example 12-4 looks like after translation. Unlike the previous example, the column definition is not changed.
Example 12-7 example_es.xml with a Language Attribute
<?xml version="1.0"?> <table xml:lang="es" name="translated_messages"> <!-- Specify the unique identifier --> <lookup-key> <column name="message_id" /> <column name="language_id" /> </lookup-key> <!-- Specify the columns into which data will be inserted --> <columns> <column name="message_id" type="number"/> <column name="language_id" type="string" language="%x"/> : :
If you use a text editor or a traditional text-based translation tool during the translation process, it is important to maintain the encoding of the document. After a document is translated, it may be in a different encoding from the original. As explained in "XML Declaration in DLF", If the translated document is in an encoding other than Unicode, then add the encoding declaration to the XML declaration on the first line. A declaration for non-Unicode encoding looks like the following:
<?xml version="1.0" encoding="ISO-8859-15"?>
To ensure that the translation process does not lose syntactic integrity, process the document as XML. Otherwise, you can check the format by specifying the -v
option of the command-line interface. If a syntactic error exists, the utility prints the location and description of the error. You must fix errors for the data transfer to succeed.
Suppose that you want to load the sample documents in Example 12-3 and Example 12-8 into the translated_messages
table that you created in Example 12-1. You can use the sample program in Example 12-8, which you can find in the TransX demo directory, to load the data.
Example 12-8 txdemo1.java
// Copyright (c) 2001 All rights reserved Oracle Corporation import oracle.xml.transx.*; public class txdemo1 { /** * Constructor */ public txdemo1() { } /** * main * @param args * * args[0] : connect string * args[1] : username * args[2] : password * args[3+] : xml file names */ public static void main(String[] args) throws Exception { // instantiate a transx class TransX transx = loader.getLoader(); // start a data loading session transx.open( args[0], args[1], args[2] ); // specify operation modes transx.setLoadingMode( LoadingMode.SKIP_DUPLICATES ); transx.setValidationMode( false ); // load the dataset(s) for ( int i = 3 ; i < args.length ; i++ ) { transx.load( args[i] ); } // cleanup transx.close(); } }
The txdemo1.java
program follows these steps:
Create a TransX loader object. For example:
TransX transx = loader.getLoader();
Open a data loading session. The first three command-line parameters are the JDBC connect string, database username, and database password. These parameters are passed to the TransX.open()
method. The program includes the following statement:
transx.open( args[0], args[1], args[2] );
Configure the TransX loader. The program configures the loader to skip duplicate rows and to validate the input dataset. The program includes the following statements:
transx.setLoadingMode( LoadingMode.SKIP_DUPLICATES ); transx.setValidationMode( false );
Load the data. The first three command-line parameters specify connection information; any additional parameters specify input XML documents. The program invokes the load()
method for every specified document:
for ( int i = 3 ; i < args.length ; i++ ) { transx.load( args[i] ); }
Close the data loading session. The program includes the following statement:
transx.close();
After compiling the program with javac
, you can run it from the command line. The following example uses the Java thin driver to connect to instance mydb
on port 1521
of computer myhost
. It connects to the user schema and loads the XML documents example.xml and example_es.xml:
java txdemo1 "jdbc:oracle:thin:@//myhost:1521/mydb" user -pw example.xml
example_es.xml
In building a multilingual software system, translations usually become available at a later stage of development. They also tend to evolve over a period of time. If you need to add messages to the database, then you can add new rows in your <dataset>
definition by running the TransX utility again. TransX recognizes which rows are new and inserts only the new messages based on the columns specified in the <lookup-key>
section. If some messages are updated, then run TransX with the -u
option to update existing rows with the data specified in XML, as shown in the following example:
transx -u "jdbc:oracle:thin:@//myhost:1521/mydb" user -pw example.xml
example_es.xml
After using the program in Example 12-8 to load the data, you can query the translated_messages
table to see the results. The results should look like the following:
MESSAGE_ID LANGUAGE_ID MESSAGE ---------- ----------- ---------------------------------- 1 us Welcome to System X 1 es Bienvenido al Sistema X 2 us Please enter username and password 2 es Porfavor entre su nombre de usuario y su contraseña
An application can retrieve a message in a specific language by using the language_id
and message_id
columns in a WHERE
clause. For example, you can execute the following query:
SELECT message FROM translated_messages WHERE message_id = 2 AND language_id = 'es'; MESSAGE ---------------------------------- Porfavor entre su nombre de usuario y su contraseña
This chapter contains these topics:
The Oracle XML JavaBeans are a set of XML components that you can use in Java applications and applets.
This section contains the following topics:
This chapter assumes that you are familiar with the following technologies:
JavaBeans. JavaBeans components, or Beans, are reusable software components that can be manipulated visually in a builder tool.
Java Database Connectivity (JDBC). Database connectivity is included with the XDK JavaBeans. The beans can connect directly to a JDBC-enabled database to retrieve and store XML and XSL files.
Document Object Model (DOM). DOM is an in-memory tree representation of the structure of an XML document.
Simple API for XML (SAX). SAX is a standard for event-based XML parsing.
XML Schema language. Refer to Chapter 7, "Using the Schema Processor for Java" for an overview and links to suggested reading.
The XDK JavaBeans require version 1.2 or higher of the XDK and can be used with any version of JDK 1.2 or above. All of the XDK beans conform to the Sun JavaBeans specification and include the required BeanInfo
class that extends java.beans.SimpleBeanInfo
.
The JavaBeans 1.01 specification, which describes JavaBeans as present in JDK 1.1, is available at the following URL:
http://java.sun.com/products/javabeans/docs/spec.html
The additions for the Java 2 platform to the JavaBeans core specification provide developers with standard means to create more sophisticated JavaBeans components. The JavaBeans specifications for Java 2 are available at the following URL:
http://java.sun.com/products/javabeans/glasgow/index.html
The Oracle XDK JavaBeans facilitate the addition of GUIs to XML applications. Bean encapsulation includes documentation and descriptors that you can access directly from Java IDEs such as Oracle JDeveloper.
The XDK includes the following beans:
The oracle.xml.async.DOMBuilder
bean constructs a DOM tree from an XML document. The DOMBuilder
JavaBean encapsulates the XML parser for Java DOMParser
class with a bean interface and enhances by supporting asynchronous parsing. By registering a listener, Java programs can initiate parsing of large or successive documents and immediately return control to the caller.
One of the main benefits of this bean is increased efficiency when parsing multiple files, especially if the files are large. DOMBuilder
can also provide asynchronous parsing in a background thread in interactive visual applications. Without asynchronous parsing, the GUI is useless until the document to be parsed. With DOMBuilder, the application calls the parse method and then resumes control. The application can display a progress bar, allow the user to cancel the parse, and so forth.
The oracle.xml.async.XSLTransformer
bean supports asynchronous transformation. It accepts an XML document, applies an XSLT stylesheet, and creates an output file. The XSLTransformer
JavaBean enables you to transform an XML document to almost any text-based format, including XML, HTML, and DDL. This bean can also be used as the basis of a server-side application or servlet to render an XML document, such as an XML representation of a query result, into HTML for display in a browser.
The main benefit of the XSLTransformer
bean is that it can transform multiple files in parallel. Like DOMBuilder
, you can also use it in visual applications to avoid long periods of time when the GUI is nonresponsive. By implementing the XSLTransformerListener interface, the calling application receives notification when the transformation completes.
The oracle.xml.dbaccess.DBAccess
bean maintains CLOB
tables that contain multiple XML and text documents. You can use it when you need to store and retrieve XML documents in the database, but do not need to process them within the database. Java applications that use the DBAccess bean connect to the database through JDBC. Note that XML documents stored in CLOB
tables that are not of type XMLType
do not have their entities expanded.
The DBAccess
bean enables you to do perform the following tasks:
Create and delete tables of type CLOB
.
Query the contents of CLOB
tables.
Perform INSERT
, UPDATE
, and DELETE
operations on XML documents stored in CLOB
tables.
The oracle.xml.xmldbaccess.XMLDBAccess
bean extends the DBAccess
bean to support XML documents stored in XMLType
tables. The class provides methods to list, delete, or retrieve XMLType
instances and their tables. For example, the getXMLXPathTextData()
method retrieves the value of an XPath expression from an XML document.
DBAccess
JavaBean maintains XMLType
tables that can hold multiple XML and text documents. Each XML or text document is stored as a row in the table. The table is created with the following SQL statement:
CREATE TABLE (FILENAME CHAR( ) UNIQUE, FILEDATA SYS.XMLType);
The FILENAME
field holds a unique string used as a key to retrieve, update, or delete the row. Document text is stored in the FILEDATA
field.
The XMLDBAccess
bean performs the following tasks:
Creates and deletes XMLType
tables
Lists the contents of an XMLType
column
Performs INSERT
, UPDATE
, and DELETE
operations on XML documents stored in XMLType
tables
When comparing XML documents, it is usually unhelpful to compare them character by character. Most XML comparisons are concerned with differences in structure and significant textual content, not differences in whitespace. The oracle.xml.differ.XMLDiff
bean performs the following useful tasks:
Constructs and compares the DOM trees for two input XML documents and indicates whether the documents are different.
Provides a graphical display of the differences between two XML files. Specifically, you can see node insert, delete, modify, or move.
Generates an XSLT stylesheet that can convert one of the input XML documents into the other document.
The XMLDiff
bean is especially useful in pipeline applications. For example, an application could update an XML document, compare it with a previous version of the document, and store the XSLT stylesheet that shows the differences between them.
As explained in "Compressing XML", the Oracle XML parser includes a compressor that can serialize XML document objects as binary streams. Although a useful tool, compression with XML parser has the following disadvantages:
When XML data is deserialized, it must be reparsed.
The encapsulation of XML data in tags greatly increase its size.
The oracle.xml.xmlcomp.XMLCompress
bean is an encapsulation of the XML compression functionality. It provides the following advantages when serializing and deserializing XML:
It encapsulates the method that serializes the DOM, which results in a stream.
XML processors can regenerate the DOM from the compressed stream without reparsing the XML.
The bean supports compression and decompression of input XML parsed by DOMParser
or SAXParser
. DOM compression supports inputs of type XMLType
, CLOB
, and BLOB
.
To use different parsing options, parse the document before input and then pass the XMLDocument
object to the compressor bean. The compression factor is a rough value based on the file size of the input XML file and the compressed file. The limitation of the compression factor method is that it can only be used when the compression is performed with java.io.File
objects as parameters.
The oracle.xml.schemavalidator.XSDValidator
bean encapsulates the XSDValidator
class and adds capabilities for validating a DOM tree. One of the most useful features of this bean concerns validation errors. If the application throws a validation error, the getStackList()
method returns a list of DOM tree paths that lead to the invalid node. Nodes with errors are returned in a vector of stack trees in which the top element of the stack represents the root node. You can obtain child nodes by pulling them from the stack. To use getStackList()
you must use instantiate the java.util.Vector
and java.util.Stack
classes.
This section contains the following topics:
This section describes the program flow of Java applications that use the more useful beans: DOMBuilder
, XSLTransformer
, XMLDBAccess
, and XMLDiff
. The section contains the following topics:
The DOMBuilder
class implements an XML 1.0 parser according to the W3C recommendation. It parses an XML document and builds a DOM tree. The parsing is done in a separate thread. The DOMBuilderListener
interface must be used for notification when the tree is built.
When developing applications that use this bean, you should import the following subpackages:
oracle.xml.async
, which provides asynchronous Java beans for DOM building
oracle.xml.parser.v2
, which provides APIs for SAX, DOM, and XSLT
The oracle.xml.parser.v2
subpackage is described in detail in Chapter 4, "XML Parsing for Java". The most important DOM-related classes and interfaces in the javax.xml.async
package are described in Table 10-1.
Table 10-1 javax.xml.async DOM-Related Classes and Interfaces
Class/Interface | Description |
---|---|
|
Encapsulates an XML parser to parse an XML document and build a DOM tree. The parsing is done in a separate thread. The |
|
Instantiates the event object that |
|
Must be implemented so that the program can receive notifications about events during the asynchronous parsing. The class implementing this interface must be added to the |
|
Defines the error event that is sent when parse exception occurs. |
|
Must be implemented so that the program can receive notifications when errors are found during parsing. The class implementing this interface must be added to the |
Figure 10-1 depicts the basic process of an application that uses the DOMBuilder
JavaBean.
Figure 10-1 shows the following stages of XML processing:
Parse the input XML document. The program can receive the XML document as a file, string buffer, or URL.
Add the DOMBuilder
listener. The program invokes the method DOMBuilder.addDOMBuilderListener(DOMBuilderListener)
.
Parse the XML document. The program invokes the DOMBuilder.parse()
method.
Optionally, process the parsed result further.
Call the listener when the program receives an asynchronous call. The listener, which must implement the DOMBuilderListener
interface, is called by invoking the DOMBuilderOver()
method.
The available DOMBuilderListener
methods are:
Fetch the DOM. Invoke the DOMBuilder.getDocument()
method to fetch the resulting DOM document and output it.
The XSLTransformer
bean encapsulates the Java XML parser XSLT processing engine with a bean interface and extends its functionality to permit asynchronous transformation. By registering a listener, your Java application can transform large and successive documents by having the control returned immediately to the caller.
When developing applications that use this bean, you should import the following subpackages:
oracle.xml.async
, which provides asynchronous Java beans for XSL transformations
oracle.xml.parser.v2
, which provides APIs for XML parsing SAX, DOM, and XSLT
The oracle.xml.parser.v2 subpackage
is described in detail in Chapter 4, "XML Parsing for Java". The most important XSL-related classes and interfaces in the javax.xml.async
package are described in Table 10-2.
Table 10-2 javax.xml.async XSL-Related Classes and Interfaces
Class/Interface | Description |
---|---|
|
Applies XSL transformation in a background thread. |
|
Represents the event object used by |
|
Must be implemented so that the program can receive notifications about events during asynchronous transformation. The class implementing this interface must be added to the |
|
Instantiates the error event object that |
|
Must be implemented so that the program can receive notifications about error events during the asynchronous transformation. The class implementing this interface must be added to the |
Figure 10-2 illustrates XSLTransformer
bean usage.
Figure 10-2 XSLTransformer JavaBean Usage
Figure 10-2 goes through the following stages:
Input an XSLT stylesheet and XML instance document.
Add an XSLT listener. The program invokes the XSLTransfomer.addXSLTransformerListener()method
.
Apply the stylesheets. The XSLTransfomer.processXSL()
method initiates the XSL transformation in the background.
Optionally, perform further processing with the XSLTransformer
bean.
Call the XSLT listener when the program receives an asynchronous call. The listener, which must implement the XSLTransformerListener
interface, is called by invoking the xslTransformerOver()
method.
Fetch the result of the transformation. Invoke the XSLTransformer.getResult()
method to return the XML document fragment for the resulting document.
Output the XML document fragment.
When developing applications that use the XMLDBAccess
bean, you should use the following subpackages:
oracle.xml.xmldbaccess
, which includes the XMLDBAccess
bean
oracle.xml.parser.v2
, which provides APIs for XML parsing SAX, DOM, and XSLT
The oracle.xml.parser.v2 subpackage
is described in detail in Chapter 4, "XML Parsing for Java". Some of the more important methods in the XMLDBAccess
class are described in Table 10-3.
Table 10-3 XMLDBAccess Methods
Class/Interface | Description |
---|---|
|
Creates an |
|
Inserts a text file as a row in an |
|
Replaces a text file as a row in an |
|
Retrieves all XML tables with names starting with a specified string. |
|
Retrieves text file from an |
|
Retrieves the text data based on the XPath expression from an |
Figure 10-3 illustrates typical XMLDBAccess
bean usage. It shows how the DBAccess
bean maintains and manipulates XML documents stored in XMLType
s.
For example, an XMLDBAaccess
program could process XML documents in the following stages:
Create an XMLType
table. Invoke createXMLTypeTable()
by passing it database connection information and a table name.
List the XMLType
tables. In voke getXMLTypeTableNames()
by passing it database connection information and an empty string.
Load XML data into the table. Invoke replaceXMLTypeData()
by passing it database connection information, the table name, the XML file name, and a string containing the XML.
Retrieve the XML data into a String
. Invoke getXMLTypeData()
by passing it the connection information, the table name, and the XML file name.
Retrieve XML data based on an XPath expression. Invoke getXMLXPathTextData()
by passing it the connection information, the table name, the XML file name, and the XPath expression.
Close the connection.
When developing applications that use the XMLDiff
bean, you typically use the following subpackages:
oracle.xml.xmldiff
, which includes the XMLDiff
bean
oracle.xml.parser.v2
, which provides APIs for XML parsing SAX, DOM, and XSLT
oracle.xml.async
, which provides asynchronous Java beans for DOM building
The oracle.xml.parser.v2 subpackage
is described in detail in Chapter 4, "XML Parsing for Java". Some important methods in the XMLDiff
class are described in Table 10-4.
Table 10-4 XMLDiff Methods
Class/Interface | Description |
---|---|
|
Determines the differences between two input XML files or two XMLDocument objects. |
|
Generates an XSL file that represents the differences between the input two XML files. The first XML file can be transformed into the second XML file with the generated stylesheet. If the XML files are the same, then the XSL generated can transform the first XML file into the second XML file, where the first and second files are equivalent. Related methods are |
|
Sets the XML files that need to be compared. |
|
Gets the document root as an XMLDocument object of the first XML tree. |
|
Gets the text panel as |
Figure 10-4 illustrates typical XMLDiff
bean usage. It shows how XMLDiff
bean compares and displays the differences between input XML documents.
For example, an XMLDiff
program could process XML documents in the following stages:
Create an XMLDiff
object.
Set the files to be compared. Create File
objects for the input files and pass references to the objects to XMLDiff.setFiles()
.
Compare the documents. The diff()
method returns false
if the XML files are the same and true
if they are different.
Respond depending on the whether the input XML documents are the same or different. For example, if they are the same, invoke JOptionPane.showMessageDialog()
to print a message.
Generate an XSLT stylesheet that shows the differences between the input XML documents. For example, generateXSLDoc()
generates an XSL stylesheet as an XMLDocument
.
Display the DOM trees created by XMLDiff
.
Demo programs for the XDK JavaBeans are included in the $ORACLE_HOME/xdk/demo/java/transviewer
directory. The demos illustrate the use of the XDK beans described in "XDK JavaBeans Features" as well as some visual beans that are now deprecated. The following list shows all of the beans used in the demos:
XSLTransformer
DOMBuilder
DBAccess
XMLDBAccess
XMLDiff
XMLCompress
XSDValidator
oracle.xml.srcviewer.XMLSourceView
(deprecated)
oracle.xml.treeviewer.XMLTreeView
(deprecated)
oracle.xml.transformer.XMLTransformPanel
(deprecated)
oracle.xml.dbviewer.DBViewer
(deprecated)
Although the visual beans are deprecated, they remain useful as educational tools. Consequently, the deprecated beans are included in $ORACLE_HOME/lib/xmldemo.jar
. The nondeprecated beans are included in $ORACLE_HOME/lib/xml.jar
.
Table 10-5 lists the sample programs provided in the demo directory. The first column of the table indicates which sample program use deprecated beans.
Table 10-5 JavaBean Sample Java Source Files
Sample | File Name | Description |
---|---|---|
(deprecated) |
|
A visual application that uses the See Also: "Running sample1" |
(deprecated) |
|
A sample visual application that uses the See Also: "Running sample2" |
|
|
A nonvisual application that uses the See Also: "Running sample3" |
(deprecated) |
|
A visual application that uses the See Also: "Running sample4" |
|
This | |
|
This | |
|
|
A nonvisual application for the To use See Also: "Running sample5" |
(deprecated) |
|
A visual application that uses the See Also: "Running sample6" |
|
A class that implements the | |
|
A | |
(deprecated) |
|
A visual application that uses the See Also: "Running sample7" |
|
A simple class that pipes information from the GUI to the bean. This class is used in | |
|
A | |
|
A | |
|
A | |
(deprecated) |
|
A visual application that uses the See Also: "Running sample8" |
|
A | |
(deprecated) |
|
A visual application that uses the See Also: "Running sample9" |
|
A class that shows how to use the | |
|
|
An application that shows how to use the See Also: "Running sample10" |
Table 10-6 describes additional files that are used by the demo programs.
Table 10-6 JavaBean Sample Files
File Name | Description |
---|---|
|
An XML document used by the |
|
An XML document used by the |
|
An XML document for use by |
|
An XML document used by |
|
An XML document for use by |
|
An XSLT stylesheet for use by |
|
An XSLT stylesheet for use by |
|
A sample XML document for use in |
|
An XML document used by the |
|
An XML schema document used by the |
Documentation for how to compile and run the sample programs is located in the README
in the same directory. The basic steps are as follows:
Change into the $ORACLE_HOME/xdk/demo/java/transviewer
directory (UNIX) or %ORACLE_HOME%\xdk\demo\java\transviewer
directory (Windows).
Make sure that your environment variables are set as described in "Setting Up the Java XDK Environment". The beans require JDK 1.2 or higher. The DBViewer
and DBTransformPanel
beans require JDK 1.2.2 when rendering HTML. Prior versions of the JDK may not render HTML in the result buffer properly.
Edit the Makefile
(UNIX) or Make.bat
(Windows) for your environment. In particular, do the following:
Change the JDKPATH
in the Makefile
to point to your JDK path.
Change PATHSEP
to the appropriate path separator for your operating system.
Change the HOSTNAME
, PORT
, SID
, USERID
, and PASSWORD
parameters so that you can connect to the database through the JDBC thin driver. These parameters are used in sample4
and sample5
.
Run make
(UNIX) or Make.bat
(Windows) at the system prompt to generate the class files.
Run gmake
as follows to run the demos:
gmake sample1 gmake sample2 gmake sample3 gmake sample4 gmake sample5 gmake sample6 gmake sample7 gmake sample8 gmake sample9 gmake sample10
The following sections explain how to run the demos.
Sample1
is the program that uses the XMLTransViewer
bean. You can run the program manually as follows:
java XMLTransformPanelSample
You can use the program to import and export XML files from Oracle database, store XSL transformation files in the database, and apply stylesheets to XML interactively. To use the database connectivity feature in this program, you need to know the network name of the computer where the database runs, the port (usually 1521
), and the name of the Oracle instance (usually orcl
). You also need an account with CREATE TABLE
privileges. If you have installed the sample schemas, then you can use the account hr
. You can the XMLTransViewer
program to apply stylesheet transformation to XML files and display the result.The program displays a panel with tabs on the top and the bottom. The first two top tabs are used to switch between the XML buffer and the XSLT buffer. The third tab performs XSL transformation on the XML buffer and displays the result. The first two tabs on the bottom can be used to load and save data from Oracle database and from the file system. The remaining bottom tabs switch the display of the current content to tree view, XML source, edit mode and, in case of the result view after the transformation, HTML.
Sample2
is a GUI-based demo for the XMLSourceView
and XMLTreeView
beans, which are deprecated. The ViewSample
program displays the booklist.xml
file in separate source and tree views. You can run the program manually as follows:
java ViewSample
Sample3
is a nonvisual demo for the asynchronous DOMBuilder
and XSLTransformer
beans. The AsyncTransformSample
program applies the doc.xsl
XSLT stylesheet to all *.xml
files in the current directory. The program writes output to files with the extension .log
. You can run the program as follows:
java AsyncTransformSample
Sample4
is a visual demo for the DBViewer
bean, which is deprecated. It runs in the following stages:
It starts SQL*Plus, connects to the database with the USERID
and PASSWORD
specified in the Makefile
, and runs the claim.sql
script. This script creates a number of tables, views, and types for use by the DBViewSample
demo program.
It runs the DBViewSample program as follows:
java -classpath "$(MAKE_CLASSPATH)" DBViewSample
JDBC connection information is hard-coded in the DBViewClaims.java
source file, which implements a class used by the demo. Specifically, the program assumes the values for USERID
, PASSWORD
, and so forth set in the Makefile
. If your configuration is different, navigate to line 92 in DBViewClaims.java
and modify setUsername()
, setPassword()
, and so forth with values that reflect your Oracle database configuration.
Sample5
is a nonvisual demo for the XMLDBAccess
bean. It uses the XMLType objects to store XML documents inside the database.The following program connects to the database with the Java thin client, creates XMLType
tables, and loads the data from booklist.xml
. To run the program you must specify the following pieces of information as command-line arguments:
Host name (for example, myhost
)
Port number (for example, 1521
)
SID of the database (for example, ORCL
)
Database account in which the tables will be created (for example, hr
)
Password for the database account (for example, hr
)
For example, you can run the program as follows:
java XMLDBAccessSample myhost 1521 ORCL hr hr
The following text shows sample output from dbaccess.log
:
Demo for createXMLTypeTables(): Table +'testxmltype' successfully created. Demo for listXMLTypeTables(): tablenamename=TESTXMLTYPE Ne Demo for replaceXMLTypeData() (similar to insert): XML Data from +'booklist.xml' successfully replaced in table 'testxmltype'. Demo for getXMLTypeData(): XMLType data fetched: <?xml version="1.0"?> <booklist> <book isbn="1234-123456-1234"> <title>C Programming Language</title> <author>Kernighan and Ritchie</author> <publisher>EEE</publisher> <price>7.99</price> </book> ... <book isbn="1230-23498-2349879"> <title>Emperor's New Mind</title> <author>Roger Penrose</author> <publisher>Oxford Publishing Company</publisher> <price>15.99</price> </book> </booklist> Demo for getXMLTypeXPathTextData(): Data fetched using XPath exp '/booklist/book[3]': <book isbn="2137-598354-65978"> <title>Twelve Red Herrings</title> <author>Jeffrey Archer</author> <publisher>Harper Collins</publisher> <price>12.95</price> </book>
The sample6
program is a visual demo for the XMLDiff
bean. The XMLDiffSample
class invokes a GUI that enables you to choose the input data files from the File menu by selecting Compare XML Files. The Transform menu enables you to apply the generated XSLT generated to the first input XML. Select Save As in the File menu to save the output XML file, which will be the same as the second input file. By default, the program compares XMLDiffData1.txt
to XMLDiffData2.txt
and stores the XSLT output as XMLDiffSample.xsl
.
You can run the program manually as follows:
java -mx50m XMLDiffSample XMLDiffData1.txt XMLDiffData2.txt
If the input XML files use a DTD that accesses a URL outside a firewall, then modify XMLDiffSample.java
to include the proxy server settings before the setFiles()
call. For example, modify the program as follows:
/* Set proxy to access dtd through firewall */ Properties p = System.getProperties(); p.put("proxyHost", "www.proxyservername.com"); p.put("proxyPort", "80"); p.put("proxySet", "true"); /* You will also have to import java.util.*; */
The sample7
visual demo illustrates the use of the XMLCompress
bean. The compviewer
class invokes a GUI which lets the user compress and uncompress XML files and data obtained from the database. The loading options enable the user to retrieve the data either from a file system or a database. This application does not support loading and saving compressed data from the database. The compression factor indicates a rough estimate by which the XML data is reduced.
You can run the program manually as follows:
java compviewer
The sample8
demo illustrates the use of the XMLTreeViewer
bean. The XMLSchemaTreeViewer
program enables the user to view an XMLDocument
in a tree format. The user can input a schema document and validate the instance document against the schema. If the document is invalid, then the invalid nodes are highlighted with the error message. Also, the program displays a log of all the line information in a separate panel, which enables the user to edit the instance document and revaluated. Test the program with sample files purchaseorder.xml
and purchaseorder.xsd
. The instance document purchaseorder.xml
does not comply with schema defined in purchaseorder.xsd
.
You can run the program manually as follows:
java XMLSchemaTreeViewer
The sample9
demo illustrates the use of the SourceViewer
bean. The XMLSrcViewer
program enables you to view an XML document or a DTD with syntax highlighting turned on. You can validate the XML document against an input XML Schema or DTD. The DTD can be internal or external.
If the validation is successful, then you can view the instance document and XML schema or DTD in the Source View pane. If errors were encountered during schema validation, then an error log with line numbers is available in the Error pane. The Source View pane shows the XML document with error nodes highlighted.You can use sample files purchaseorder.xml
and purchaseorder.xsd
for testing XML schema validation with errors. You can use note_in_dtd.xml
with DTD validation mode to view an internal DTD with validation errors. You can run the program manually as follows:
java XMLSrcViewer
The sample10
demo illustrates the use of the XSDValidator
bean. The XSDValidatorSample
program's two input arguments are an XML document and its associated XML schema. The program displays errors occurring during validation, including line numbers.
The following program uses purchaseorder.xsd
to validate the contents of purchaseorder.xml
:
java XSDValidatorSample purchaseorder.xml purchaseorder.xsd
The XML document fails (intentionally) to validate against the schema. The program displays the following errors:
Sample purchaseorder.xml purchaseorder.xsd <Line 2, Column 41>: XML-24523: (Error) Invalid value 'abc' for attribute: 'orderDate' #document->purchaseOrder <Line 7, Column 27>: XML-24525: (Error) Invalid text 'CA' in element: 'state' #document->purchaseOrder->shipTo->state->#text <Line 8, Column 25>: XML-24525: (Error) Invalid text 'sd' in element: 'zip' #document->purchaseOrder->shipTo->zip->#text <Line 14, Column 27>: XML-24525: (Error) Invalid text 'PA' in element: 'state' #document->purchaseOrder->billTo->state->#text <Line 17, Column 22>: XML-24534: (Error) Element 'coment' not expected. #document->purchaseOrder->coment <Line 29, Column 31>: XML-24534: (Error) Element 'shipDae' not expected. #document->purchaseOrder->items->item->shipDae
This section contains the following topics:
As explained in "DOMBuilder" and "XSLTransformer", you can use XDK beans to perform asynchronous XML processing.
The AsyncTransformSample.java
program illustrates how to use both the DOMBuilder
and XSLTransformer
beans. The program implements the following methods:
runDOMBuilders()
runXSLTransformer()
saveResult()
makeXSLDocument()
createURL()
init()
exitWithError()
asyncTransform()
The basic architecture of the program is as follows:
The program declares and initializes the fields used by the class. Note that the input XSLT stylesheet is hard-coded in the program as doc.xsl
. The class defines the following fields:
String basedir = new String ("."); OutputStream errors = System.err; Vector xmlfiles = new Vector(); int numXMLDocs = 1; String xslFile = new String ("doc.xsl"); URL xslURL; XMLDocument xsldoc
The main()
method invokes the init()
method to perform the initial setup. This method lists the files in the current directory, and if it finds files that end in the extension .xml
, it adds them to a Vector
object. The implementation for the init()
method is as follows:
boolean init () throws Exception { File directory = new File (basedir); String[] dirfiles = directory.list(); for (int j = 0; j < dirfiles.length; j++) { String dirfile = dirfiles[j]; if (!dirfile.endsWith(".xml")) continue; xmlfiles.addElement(dirfile); } if (xmlfiles.isEmpty()) { System.out.println("No files in directory were selected for processing"); return false; } numXMLDocs = xmlfiles.size(); return true; }
The main()
method instantiates AsyncTransformSample
as follows:
AsyncTransformSample inst = new AsyncTransformSample();
The main()
method invokes the asyncTransform()
method. The asyncTransform()
method performs the following main tasks:
Invokes makeXSLDocument()
to parse the input XSLT stylesheet.
Calls runDOMBuilders()
to initiate parsing of the instance documents, that is, the documents to be transformed, and then transforms them.
After initiating the XML processing, the program resumes control and waits while the processing occurs in the background. When the last request completes, the method exits.
The following code shows the implementation of the asyncTransform()
method:
void asyncTransform () throws Exception { System.err.println (numXMLDocs + " XML documents will be transformed" + " using XSLT stylesheet specified in " + xslFile + " with " + numXMLDocs + " threads"); makeXSLDocument (); runDOMBuilders (); // wait for the last request to complete while (rm.activeFound()) Thread.sleep(100); }
The following sections explain the makeXSLDocument()
and runDOMBuilders()
methods.
The makeXSLDocument()
method illustrates a simple DOM parse of the input stylesheet. It does not use asynchronous parsing. The technique is the same described in "Performing Basic DOM Parsing".
The method follows these steps:
Create a new DOMParser()
object. The following code fragment from DOMSample.java
illustrates this technique:
DOMParser parser = new DOMParser();
Configure the parser. The following code fragment specifies that whitespace should be preserved:
parser.setPreserveWhitespace(true);
Create a URL
object from the input stylesheet. The following code fragment invokes the createURL()
helper method to accomplish this task:
xslURL = createURL (xslFile);
Parse the input XSLT stylesheet. The following statement illustrates this technique:
parser.parse (xslURL);
Obtain a handle to the root of the in-memory DOM tree. You can use the XMLDocument
object to access every part of the parsed XML document. The following statement illustrates this technique:
xsldoc = parser.getDocument();
The runDOMBuilders()
method illustrates how you can use the DOMBuilder
and XSLTransformer
beans to perform asynchronous processing. The parsing and transforming of the XML occurs in the background.
The method follows these steps:
Create a resource manager to manage the input XML documents. The program creates a for
loop and obtains the XML documents. The following code fragment illustrates this technique:
rm = new ResourceManager (numXMLDocs); for (int i = 0; i < numXMLDocs; i++) { rm.getResource(); ... }
Instantiate the DOM builder bean for each input XML document. For example:
DOMBuilder builder = new DOMBuilder(i);
Create a URL
object from the XML file name. For example:
DOMBuilder builder = new DOMBuilder(i); URL xmlURL = createURL(basedir + "/" + (String)xmlfiles.elementAt(i)); if (xmlURL == null) exitWithError("File " + (String)xmlfiles.elementAt(i) + " not found");
Configure the DOM builder. The following code fragment specifies the preservation of whitespace and sets the base URL for the document:
builder.setPreserveWhitespace(true); builder.setBaseURL (createURL(basedir + "/"));
Add the listener for the DOM builder. The program adds the listener by invoking addDOMBuilderListener()
.
The class instantiated to create the listener must implement the DOMBuilderListener
interface. The program provides a do-nothing implementation for domBuilderStarted()
and domBuilderError()
, but must provide a substantive implementation for domBuilderOver()
, which is the method called when the parse of the XML document completes. The method invokes runXSLTransformer()
, which is the method that transforms the XML. Refer to "Transforming the XML with the XSLTransformer Bean" for an explanation of this method.
The following code fragment illustrates how to add the listener:
builder.addDOMBuilderListener ( new DOMBuilderListener() { public void domBuilderStarted(DOMBuilderEvent p0) {} public void domBuilderError(DOMBuilderEvent p0) {} public synchronized void domBuilderOver(DOMBuilderEvent p0) { DOMBuilder bld = (DOMBuilder)p0.getSource(); runXSLTransformer (bld.getDocument(), bld.getId()); } } );
Add the error listener for the DOM builder. The program adds the listener by invoking addDOMBuilderErrorListener()
.
The class instantiated to create the listener must implement the DOMBuilderErrorListener
interface. The following code fragment show the implementation:
builder.addDOMBuilderErrorListener ( new DOMBuilderErrorListener() { public void domBuilderErrorCalled(DOMBuilderErrorEvent p0) { int id = ((DOMBuilder)p0.getSource()).getId(); exitWithError("Error occurred while parsing " + xmlfiles.elementAt(id) + ": " + p0.getException().getMessage()); } } );
Parse the document. The following statement illustrates this technique:
builder.parse (xmlURL); System.err.println("Parsing file " + xmlfiles.elementAt(i));
When the DOM parse completes, the DOM listener receives notification. The domBuilderOver()
method implements the behavior in response to this event. The program passes the DOM to the runXSLTransformer()
method, which initiates the XSL transformation.
The method follows these steps:
Instantiate the XSLTransformer
bean. This object performs the XSLT processing. The following statement illustrates this technique:
XSLTransformer processor = new XSLTransformer (id);
Create a new stylesheet object. For example:
XSLStylesheet xsl = new XSLStylesheet (xsldoc, xslURL);
Configure the XSLT processor. For example, the following statement sets the processor to show warnings and configures the error output stream:
processor.showWarnings (true); processor.setErrorStream (errors);
Add the listener for the XSLT processor. The program adds the listener by invoking addXSLTransformerListener()
.
The class instantiated to create the listener must implement the XSLTransformerListener
interface. The program provides a do-nothing implementation for xslTransformerStarted()
and xslTransformerError()
, but must provide a substantive implementation for xslTransformerOver()
, which is the method called when the parse of the XML document completes. The method invokes saveResult()
, which prints the transformation result to a file.
The following code fragment illustrates how to add the listener:
processor.addXSLTransformerListener ( new XSLTransformerListener() { public void xslTransformerStarted (XSLTransformerEvent p0) {} public void xslTransformerError(XSLTransformerEvent p0) {} public void xslTransformerOver (XSLTransformerEvent p0) { XSLTransformer trans = (XSLTransformer)p0.getSource(); saveResult (trans.getResult(), trans.getId()); } } );
Add the error listener for the XSLT processor. The program adds the listener by invoking addXSLTransformerErrorListener()
.
The class instantiated to create the listener must implement the XSLTransformerErrorListener
interface. The following code fragment show the implementation:
processor.addXSLTransformerErrorListener ( new XSLTransformerErrorListener() { public void xslTransformerErrorCalled(XSLTransformerErrorEvent p0) { int i = ((XSLTransformer)p0.getSource()).getId(); exitWithError("Error occurred while processing " + xmlfiles.elementAt(i) + ": " + p0.getException().getMessage()); } } );
Transform the XML document with the XSLT stylesheet. The following statement illustrates this technique:
processor.processXSL (xsl, xml);
As explained in "XMLDiff", you can use XDK beans to compare the structure and significant content of XML documents.
The XMLDiffSample.java
program illustrates how to use the XMLDiff
bean. The program implements the following methods:
showDiffs()
doXSLTransform()
createURL()
The basic architecture of the program is as follows:
The program declares and initializes the fields used by the class. Note that one field is of type XMLDiffFrame
, which is the class implemented in the XMLDiffFrame.java
demo. The class defines the following fields:
protected XMLDocument doc1; /* DOM tree for first file */ protected XMLDocument doc2; /* DOM tree for second file */ protected static XMLDiffFrame diffFrame; /* GUI frame */ protected static XMLDiffSample dfxApp; /* XMLDiff sample application */ protected static XMLDiff xmlDiff; /* XML diff object */ protected static XMLDocument xslDoc; /* parsed xsl file */ protected static String outFile = new String("XMLDiffSample.xsl"); /* output xsl file name */
The main()
method creates an XMLDiffSample
object as follows:
dfxApp = new XMLDiffSample();
The main()
method adds and initializes a JFrame
to display the output of the comparison. The following code illustrates this technique:
diffFrame = new XMLDiffFrame(dfxApp); diffFrame.addTransformMenu();
The main()
method instantiates the XMLDiff
bean. The following code illustrates this technique:
xmlDiff = new XMLDiff();
The main()
method invokes the showDiffs()
method. This method performs the following tasks:
Invokes XMLDiff.diff()
to compare the input XML documents.
Generates and displays an XSLT stylsheet that can transform one input document into the other document.
The following code fragment shows the showDiffs()
method call:
if (args.length == 3) outFile = args[2]; if(args.length >= 2) dfxApp.showDiffs(new File(args[0]), new File(args[1])); diffFrame.setVisible(true);
The following section explains the showDiffs()
method.
The showDiffs()
method illustrates the use of the XMLDiff
bean.
The method follows these steps:
Set the files for the XMLDiff
processor. The following statement illustrates this technique:
xmlDiff.setFiles(file1, file2);
Compare the files. The diff()
method returns a boolean value that indicates whether the input documents have identical structure and content. If they are equivalent, then the method prints a message to the JFrame
implemented by the XMLDiffFrame
class. The following code fragment illustrates this technique:
if(!xmlDiff.diff()) { JOptionPane.showMessageDialog ( diffFrame, "Files are equivalent in XML representation", "XMLDiffSample Message", JOptionPane.PLAIN_MESSAGE ); }
Generate a DOM for the XSLT stylesheet that shows the differences between the two documents. The following code fragment illustrates this technique:
xslDoc = xmlDiff.generateXSLDoc();
Display the documents in the JFrame
implemented by XMLDiffFrame
. Note that XMLDiffFrame
instantiates the XMLSourceView
bean, which is deprecated. The method follows these steps:
Create the source pane for the input documents. Pass the DOM handles of the two documents to the diffFrame
object to make the source pane:
diffFrame.makeSrcPane(xmlDiff.getDocument1(), xmlDiff.getDocument2());
Create the pane that shows the differences between the documents. Pass references to the text panes to diffFrame
as follows:
diffFrame.makeDiffSrcPane(new XMLDiffSrcView(xmlDiff.getDiffPane1()), new XMLDiffSrcView(xmlDiff.getDiffPane2()));
Create the pane for the XSLT stylesheet. Pass the DOM of the stylesheet as follows:
diffFrame.makeXslPane(xslDoc, "Diff XSL Script"); diffFrame.makeXslTabbedPane();
This part contains chapters describing how the Oracle XDK is used for development in C.
This part contains the following chapters: