Using XML in Oracle Database Applicationssaleemsyed4u.weebly.com/uploads/8/5/7/0/8570245/xml.pdf ·...

25
Using XML in Oracle Database Applications Using XML in Oracle Database Applications Part 1: About XML This document presents a basic overview of XML and describes its key uses in database applications. Overview XML stands for eXtensible Markup Language. Ratified by the World Wide Web Consortium (W3C), XML is quickly becoming the standard way to identify and describe data on the web because it has proved broadly implementable and easy to deploy. Like HTML, XML is a subset of SGML (Structured Generalized Markup Language), optimized for delivery over the web. Unlike HTML, which tags elements in web pages for presentation by a browser, e.g. <bold>Oracle</bold>, XML tags elements as data, e.g. <company>Oracle</company>. For example, you can use XML to give context to words and values in web pages, identifying them as data instead of simple textual or numeric elements. The following is an HTML code example followed by a corresponding XML example. The example shows employee data: employee number, name, job and salary. In the XML code, note the addition of XML data tags and the nested structure of the elements. HTML Example <table> <tr><td>EMPNO</td><td>ENAME</td><td>JOB</td><td>SAL</td></tr> <tr><td>7654</td><td>MARTIN</td><td>SALESMAN</td><td>1250</td></tr> <tr><td>7788</td><td>SCOTT</td><td>ANALYST</td><td>3000</td></tr> </table> Corresponding XML Example <?xml version="1.0"?> <EMPLIST> <EMP> <EMPNO>7654</EMPNO> <ENAME>MARTIN</ENAME> <JOB>SALESMAN</JOB> <SAL>1250</SAL> </EMP> <EMP> <EMPNO>7788</EMPNO> <ENAME>SCOTT</ENAME> <JOB>ANALYST</JOB> <SAL>3000</SAL> </EMP>

Transcript of Using XML in Oracle Database Applicationssaleemsyed4u.weebly.com/uploads/8/5/7/0/8570245/xml.pdf ·...

Page 1: Using XML in Oracle Database Applicationssaleemsyed4u.weebly.com/uploads/8/5/7/0/8570245/xml.pdf · Using XML in Oracle Database Applications Part 1: About XML This document presents

Using XML in Oracle Database ApplicationsUsing XML in Oracle Database Applications

Part 1: About XML This document presents a basic overview of XML and describes its key uses in database applications. Overview XML stands for eXtensible Markup Language. Ratified by the World Wide Web Consortium (W3C), XML is quickly becoming the standard way to identify and describe data on the web because it has proved broadly implementable and easy to deploy. Like HTML, XML is a subset of SGML (Structured Generalized Markup Language), optimized for delivery over the web. Unlike HTML, which tags elements in web pages for presentation by a browser, e.g. <bold>Oracle</bold>, XML tags elements as data, e.g. <company>Oracle</company>. For example, you can use XML to give context to words and values in web pages, identifying them as data instead of simple textual or numeric elements. The following is an HTML code example followed by a corresponding XML example. The example shows employee data: employee number, name, job and salary. In the XML code, note the addition of XML data tags and the nested structure of the elements. HTML Example <table> <tr><td>EMPNO</td><td>ENAME</td><td>JOB</td><td>SAL</td></tr> <tr><td>7654</td><td>MARTIN</td><td>SALESMAN</td><td>1250</td></tr> <tr><td>7788</td><td>SCOTT</td><td>ANALYST</td><td>3000</td></tr> </table> Corresponding XML Example <?xml version="1.0"?> <EMPLIST> <EMP> <EMPNO>7654</EMPNO> <ENAME>MARTIN</ENAME> <JOB>SALESMAN</JOB> <SAL>1250</SAL> </EMP> <EMP> <EMPNO>7788</EMPNO> <ENAME>SCOTT</ENAME> <JOB>ANALYST</JOB> <SAL>3000</SAL> </EMP>

Page 2: Using XML in Oracle Database Applicationssaleemsyed4u.weebly.com/uploads/8/5/7/0/8570245/xml.pdf · Using XML in Oracle Database Applications Part 1: About XML This document presents

</EMPLIST> Presenting XML Using Style sheets A key advantage of using XML as a data source is that its presentation (such as a web page) is separate from its structure and content. The XML data defines the structure and content, and then a style sheet is applied to it to define the presentation. XML data can be presented in a variety of ways (both in appearance and organization) simply by applying different style sheets to it. For example, a different interface can be presented to different users based on user profile, browser type, or other criteria by defining a different style sheet for each different presentation style. Or, style sheets can be used to transform XML data into a format tailored to the specific application that receives and processes the data. Style sheets may be applied either on the server or on the client. The style sheet language of XML is also the subject of a W3C standard's effort. The eXtensible Style sheet Language, XSL, provides for style sheets that allow you to transform XML into HTML or other text-based formats, rearrange or filter data, or convert it to XML that conforms to another DTD-an important capability for allowing different applications to share data. Extensibility and Document Type Definitions Another key advantage of XML over HTML is that it leaves the specification of the tags and how they can be used to the user You apply XML by creating your own tags to represent the meaning and structure of your data. Tags may be defined by using them in an XML document or they may be formally defined in a Document Type Definition (DTD). As your data or application requirements change, you can change or add tags to reflect new data types or extend existing ones. The following is a simple DTD for the XML example above. Example DTD <!DOCTYPE EMPLIST[> <!ELEMENT EMPLIST (EMP)*> <!ELEMENT EMP (EMPNO, ENAME, JOB, SAL)> <!ELEMENT EMPNO (#PCDATA)> <!ELEMENT ENAME (#PCDATA)> <!ELEMENT JOB (#PCDATA)> <!ELEMENT SAL (#PCDATA)> ]> Well-Formed and Valid XML Documents An XML document that conforms to the structural and notational rules of XML is considered well-formed. A well-formed XML document does not have to contain or

Page 3: Using XML in Oracle Database Applicationssaleemsyed4u.weebly.com/uploads/8/5/7/0/8570245/xml.pdf · Using XML in Oracle Database Applications Part 1: About XML This document presents

reference a DTD, but rather can implicitly define its data elements and their relationships. Well-formed XML documents must follow these rules: The document must start with the XML declaration <?xml version="1.0"> All elements must be contained within one root element. Elements must be nested in a tree structure without overlapping All non-empty elements must have start and end tags Well-formed XML documents that also conform to a DTD are considered valid. When an XML document containing or referencing a DTD is parsed, the parsing application verifies that the XML conforms to the DTD and is therefore valid, which allows the parsing application to process it with the assurance that all of the data follows the rules defined in the DTD. When storing data from an XML document in a database, the DTD can be used to validate its structure ensuring its data elements will map to the corresponding columns in the database table. If an XML document is generated by reading data from the database and constructing the XML based upon its schema, the resulting XML document will be implicitly valid. By design, it will conform to the underlying table structure that generated it. Future Additions to XML XML is evolving. A schema language is being developed by the W3C XML Schema Working Group, to define the structure, content, and semantics of XML documents. The XML Schema specification will address areas that are currently lacking in DTDs, including the definition and validation of data types. Other W3C Working Groups are working the XPath, XLink and XPointer, which will provide scalable and maintainable hyperlinking and addressing capabilities. Key Uses of XML There are many potential uses of XML in Internet applications. Two of the most compelling uses that involve database applications are customizing the presentation of data and exchanging business data among applications. Customizing the Presentation of Data XML is beginning to be increasingly used to enable customized presentation of data for different browsers, devices, and users. By using XML documents along with XSL stylesheets on either the client, middle-tier, or server, you can transform, organize, and present XML data tailored to individual users for a variety of client devices, including graphical and non-graphical web browsers, personal digital assistants (PDAs) like the Palm Pilot, digital cell phones, and pagers, among others. In doing so, you can focus your business applications on business operations, without concern for the kind of output devices that will present the data, now or in the future. Using XML and XSL also makes it easier to create and manage dynamic web sites. You can change the look and feel

Page 4: Using XML in Oracle Database Applicationssaleemsyed4u.weebly.com/uploads/8/5/7/0/8570245/xml.pdf · Using XML in Oracle Database Applications Part 1: About XML This document presents

simply by changing the XSL stylesheet, without having to modify the underlying business logic or database code. As you target new users and devices, you can simply design new XSL stylesheets as needed. For more information, see Customizing Data Presentation. Exchanging Business Data Among Applications A challenge for business application developers is to tie together data generated by applications from different vendors and different application domains. XML makes this kind of data exchange among applications simpler to do by focusing on the data and its context without tying it to specific network or communication protocols. Through the use XML and XSL transformations, applications can interchange data without having to manage and interpret proprietary or incompatible data formats. For more information about data exchange using XML, see Exchanging Business Data Among Applications. Resources There are many excellent articles, whitepapers, and books that describe all facets of XML technology. Many of these are available on the world wide web. The following are links to some of the most useful resources: XML, Java, and the Future of the Web by Jon Bosak, Sun Microsystems XML for the Absolute Beginner by Mark Johnson, JavaWorld XML And Databases by Ronald Bourret, Technical University of Darmstadt World Wide Web Consortium (W3C) XML Specifications XML.com (a broad collection of XML resources and commentary) Annotated XML Specification by Tim Bray, XML.com The XML FAQ by the W3C XML Special Interest Group XML.org (the industry clearing house for XML DTDs that allow companies to exchange XML data) xDev (the DataChannel XML Developer pages)

Page 5: Using XML in Oracle Database Applicationssaleemsyed4u.weebly.com/uploads/8/5/7/0/8570245/xml.pdf · Using XML in Oracle Database Applications Part 1: About XML This document presents

Using XML in Oracle DatabaseUsing XML in Oracle Database Part 2: About Oracle XML Products In Part 1, we introduced you to XML. In this document, we describe Oracle products for XML-enabling database applications. Overview Oracle provides several components, utilities, and interfaces you can use to take advantage of XML technology in your database applications. Which products you use depends on your application requirements, programming preferences, and development and deployment environments. Some of the key Oracle products that support XML in database applications include: Oracle8i and interMedia XML Parsers and XSL Processors (Java, C, C++, and PL/SQL) XML Class Generators (Java and C++) XML SQL Utility for Java XSQL Servlet XML Transviewer Beans The XML Parsers, XSL Processors, XML Class Generator, and XML Transviewer Beans are packaged together in the Oracle XML Developer's Kit (XDK). You can run the these components in the Oracle8i server, on a middle tier such as Oracle Application Server, or on the client. Oracle8i and interMedia Oracle8i includes native support for Internet standards, including Java and XML. In fact, you can run Oracle XML components and applications built with them inside the database itself using Oracle JServer, Oracle8i's built-in Java Virtual Machine. For devices and applications that require a smaller database footprint, you can use Oracle8i Lite to store and retrieve XML data. You can use interMedia Text to perform searches on XML documents stored in Oracle8i by indexing the XML as plain text, or as document sections for more precise searches, such as find "Oracle WITHIN title" where "title" is a section of the document. You can also use Oracle8i's object-relational features to capture the complex structure of XML data. This enables the XML data to be operated and managed on a desired level of granularity, and it lends more readily to more efficient construction of dynamic XML documents from the resulting fragments. When storing XML in Oracle8i, there are three basic strategies:

Page 6: Using XML in Oracle Database Applicationssaleemsyed4u.weebly.com/uploads/8/5/7/0/8570245/xml.pdf · Using XML in Oracle Database Applications Part 1: About XML This document presents

storing XML document as a single, intact object with its tags in a CLOB or BLOB storing the XML document as data and distributing it untagged across object-relational tables combining XML documents and data using views Depending on the structure of the XML document, you may choose one of these approaches. Storing XML Documents as Documents Storing an intact XML document in a CLOB or BLOB is a good strategy if the XML document contains static content that will only be updated by replacing the entire document. Examples include written text such as articles, advertisements, books, legal contracts, and so on. Documents of this nature are known as document-centric and are delivered from the database as a whole. Storing this kind of document intact within Oracle8i gives you the advantages of an industry-proven database and its reliability over file system storage. If you choose to store an XML document outside of the database, you can still use Oracle8i features to index, query, and efficiently retrieve the document through the use of BFILES, URLs, and text-based indexing. Storing XML Documents as Data If the XML document has a well-defined structure and contains data that is updateable or used in other ways, the document is data-centric. Typically, the XML document contains elements or attributes that have complex structures. Examples of this kind of document include sales orders and invoices, airline flight schedules, and so on. Oracle8i, with its object-relational extensions has the ability to capture the structure of the data in the database using object types, object references, and collections. There are two options for storing and preserving the structure of the XML data in an object-relational form: store the attributes of the elements in a relational table and define object views to capture the structure of the XML elements store the structured XML elements in an object table Once stored in the object-relational form, the data can be easily updated, queried, rearranged, and reformatted as needed using SQL. The XML SQL Utility provides the means to then store an XML document by mapping it to the underlying object-relational storage, and conversely, provides the ability retrieve the object-relational data as an XML document. If an XML document is structured, but the structure of the XML document is not compatible with the structure of the underlying database schema, you must transform the data into the correct format before writing it to the database. You can achieve this using XSL stylesheets or other programming approaches, but depending on your needs, you might want to store the data-centric XML document as an intact single object. Alternately, you can define object views corresponding to the various XML document

Page 7: Using XML in Oracle Database Applicationssaleemsyed4u.weebly.com/uploads/8/5/7/0/8570245/xml.pdf · Using XML in Oracle Database Applications Part 1: About XML This document presents

structure and define instead-of triggers to perform the appropriate transformation and update the base data. Combining XML Documents and Data Using Views Finally, if you have a combination of structured and unstructured XML data, but still want to view and operate on it as a whole, you can use Oracle8i views. Views enable you to construct an object on the "fly" by combining XML data stored in a variety of ways. So, you can store structured data (such as employee data, customer data, and so on) in one location within object -relational tables, and store related unstructured data (such as descriptions and comments) within a CLOB. When you need to retrieve the data as a whole, you simply construct the structure from the various pieces of data with the use of type constructors in the view's select statement. The XML SQL Utility then enables retrieving the constructed data from the view as a single XML document. XML Parsers Oracle provides a set of XML parsers for Java, C, C++, and PL/SQL. Each of these parsers is a stand-alone XML component that parses an XML document (or a standalone DTD) so that it can be processed by an application. The parsers support the DOM (Document Object Model) and SAX (Simple API for XML) interfaces, XML Namespaces, validating and non-validating modes, and XSL transformations. The parsers are available on all Oracle platforms.

XSL Transformation Support The v2 versions of the XML Parsers include an integrated XSL Transformation (XSLT) Processor for transforming XML data using XSL stylesheets. Using the XSLT processor, you can transform XML documents from XML to XML, HTML, or virtually any other text-based format.

Page 8: Using XML in Oracle Database Applicationssaleemsyed4u.weebly.com/uploads/8/5/7/0/8570245/xml.pdf · Using XML in Oracle Database Applications Part 1: About XML This document presents

Namespace Support The Java, C, and C++ parsers also support XML Namespaces. Namespaces are a mechanism to resolve or avoid name collisions between element types (tags) or attributes in XML documents. This mechanism provides "universal" namespace element types and attribute names whose scope extends beyond the containing document. Such tags are qualified by uniform resource identifiers (URIs), such as <oracle:EMP xmlns:oracle="http://www.oracle.com/xml"/>. For example, namespaces can be used to identify an Oracle <EMP> data element as distinct from another company's definition of an <EMP> data element. This enables an application to more easily identify elements and attributes it is designed to process. The Java, C, and C++ parsers support namespaces by being able to recognize and parse universal element types and attribute names, as well as unqualified "local" element types and attribute names. Validating and Non-Validating Mode Support The Java, C, and C++ parsers can parse XML in validating or non-validating modes. In non-validating mode, the parser verifies that the XML is well-formed and parses the data into a tree of objects that can be manipulated by the DOM API. In validating mode, the parser verifies that the XML is well-formed and validates the XML data against the DTD (if any). Validation involves checking whether or not the attribute names and element tags are legal, whether nested elements belong where they are, and so on. About DOM and SAX APIs XML APIs generally fall into two categories: event-based and tree-based. An event-based API (such as SAX) uses callbacks to report parsing events to the application. The application deals with these events through customized event handlers. Events include the start and end of elements and characters. Unlike tree-based APIs, event-based APIs usually do not build in-memory tree representations of the XML documents. Therefore, in general, SAX is useful for applications that do not need to manipulate the XML tree, such as search operations, among others. For example, the following XML document:

Page 9: Using XML in Oracle Database Applicationssaleemsyed4u.weebly.com/uploads/8/5/7/0/8570245/xml.pdf · Using XML in Oracle Database Applications Part 1: About XML This document presents

<?xml version="1.0"?> <EMPLIST> <EMP> <ENAME>MARTIN</ENAME> </EMP> <EMP> <ENAME>SCOTT</ENAME> </EMP> </EMPLIST> Becomes a series of linear events: start document start element: EMPLIST start element: EMP start element: ENAME characters: MARTIN end element: EMP start element: EMP start element: ENAME characters: SCOTT end element: EMP end element: EMPLIST end document A tree-based API (such as DOM) builds an in-memory tree representation of the XML document. It provides classes and methods for an application to navigate and process the tree. In general, the DOM interface is most useful for structural manipulations of the XML tree, such as reordering elements, adding or deleting elements and attributes, renaming elements, and so on. For example, given the XML document above, the DOM would create an in-memory tree structure such as:

Page 10: Using XML in Oracle Database Applicationssaleemsyed4u.weebly.com/uploads/8/5/7/0/8570245/xml.pdf · Using XML in Oracle Database Applications Part 1: About XML This document presents

Example: Java XML Parser The following Java code uses the XML Parser for Java v2 to parse an XML document, then uses the DOM API to manipulate the XML data, and finally uses the XSLT Processor API to transform the data. import org.w3c.dom.*; import java.util.*; import java.io.*; import java.net.*; import oracle.xml.parser.v2.*; public class XSLTransform { public static void main (String args[]) throws Exception { DOMParser parser; XMLDocument xml, xsldoc, out; URL xslURL; URL xmlURL; try { if (args.length != 2) { // Pass in the names of the XSL and XML files System.err.println("Usage: java XSLTransform xslfile xmlfile"); System.exit(1); } // Parse XSL and XML documents parser = new DOMParser(); parser.setPreserveWhitespace(true); xslURL = createURL(args[0]); parser.parse(xslURL); xsldoc = parser.getDocument(); xmlURL = createURL(args[1]); parser.parse(xmlURL); xml = parser.getDocument(); // Instantiate the stylesheet XSLStylesheet xsl = new XSLStylesheet(xsldoc, xslURL); XSLProcessor processor = new XSLProcessor(); // Display any warnings that may occur processor.showWarnings(true); processor.setErrorStream(System.err); // Process XSL DocumentFragment result = processor.processXSL(xsl, xml); // Create an output document to hold the result out = new XMLDocument(); // Create a dummy document element for the output document

Page 11: Using XML in Oracle Database Applicationssaleemsyed4u.weebly.com/uploads/8/5/7/0/8570245/xml.pdf · Using XML in Oracle Database Applications Part 1: About XML This document presents

Element root = out.createElement("root"); out.appendChild(root); // Append the transformed tree to the dummy document element root.appendChild(result); // Print the transformed document out.print(System.out); } catch (Exception e) { e.printStackTrace(); } } } XML Class Generator for Java The XML Class Generator for Java creates Java source files from an XML DTD. This is useful when an application wants to send an XML message to another application based on an agreed-upon DTD or as the back end of a web form to construct and XML document. Using these classes, Java applications can construct, validate, and print XML documents that comply with the input DTD. The Class Generator works in conjunction with the Oracle XML Parser for Java, which parses the DTD and passes the parsed document to the class generator.

Example: XML Class Generator For Java This example shows how the XML Class Generator for Java can be used to process a DTD and generate classes for the DTD's elements. It then shows how to programmatically use methods of the element classes to construct a valid XML document. The Input DTD

Page 12: Using XML in Oracle Database Applicationssaleemsyed4u.weebly.com/uploads/8/5/7/0/8570245/xml.pdf · Using XML in Oracle Database Applications Part 1: About XML This document presents

The following DTD file for employee data, employee.dtd, is used as the input to the class generator. Here, the DTD specifies that the XML document root is EMP and the row element is EMP_ROW. EMP consists of one or more EMP_ROWs. Each EMP_ROW contains a required EMPNO attribute for the employee number, as well as several optional attributes such as ENAME for employee names, JOB for job type, MGR for manager, and so on. Optional attributes are followed by a "?" in the element definition: <!-- DTD for Employee Data --> <!ELEMENT EMP (EMP_ROW)*> <!ELEMENT EMP_ROW (EMPNO, ENAME?, JOB?, MGR?, HIREDATE?, SAL?, COMM?, DEPTNO?)> <!ATTLIST EMP_ROW ROWNO CDATA #REQUIRED> <!ELEMENT EMPNO (#PCDATA)> <!ELEMENT ENAME (#PCDATA)> <!ELEMENT JOB (#PCDATA)> <!ELEMENT MGR (#PCDATA)> <!ELEMENT HIREDATE (#PCDATA)> <!ELEMENT SAL (#PCDATA)> <!ELEMENT COMM (#PCDATA)> <!ELEMENT DEPTNO (#PCDATA)> Processing the DTD to Generate Java Classes The following code sample processes a DTD and generates the corresponding classes for elements in the DTD. Running the class generator on the DTD above creates Java classes for each element (EMP, EMP_ROW, EMPNO, ENAME, and so on). A Java application can then use the methods defined on these classes to create a valid XML document containing employee data. import java.io.*; import java.net.*; import oracle.xml.parser.*; import oracle.xml.classgen.*; import org.w3c.dom.Element; public class SampleMain { public SampleMain() { } public static void main (String args[]) { // validate arguments if (args.length < 1) { System.out.println("Usage: java SampleMain "+ "[-root <rootName>] <fileName>"); System.out.println("fileName\t Input file, XML document or " + "external DTD file"); System.out.println("-root <rootName> Name of the root Element " +

Page 13: Using XML in Oracle Database Applicationssaleemsyed4u.weebly.com/uploads/8/5/7/0/8570245/xml.pdf · Using XML in Oracle Database Applications Part 1: About XML This document presents

"(required if the input file is an external DTD)"); return ; } try // to open the External DTD File { // instantiate the parser XMLParser parser = new XMLParser(); if (args.length == 3) parser.parseDTD(fileToURL(args[2]), args[1]); else parser.parse(fileToURL(args[0])); XMLDocument doc = parser.getDocument(); DTD dtd = (DTD)doc.getDoctype(); String doctype_name = null; if (args.length == 3) { doctype_name = args[1]; } else { // get the Root Element name from the XMLDocument doctype_name = doc.getDocumentElement().getTagName(); } // generate the Java files... ClassGenerator generator = new ClassGenerator(); // set generate comments to true generator.setGenerateComments(true); // set output directory generator.setOutputDirectory("."); // set validating mode to true generator.setValidationMode(true); // generate java src generator.generate(dtd, doctype_name); } catch (Exception e) { System.out.println ("XML Class Generator: Error " + e.toString()); e.printStackTrace(); } }

Page 14: Using XML in Oracle Database Applicationssaleemsyed4u.weebly.com/uploads/8/5/7/0/8570245/xml.pdf · Using XML in Oracle Database Applications Part 1: About XML This document presents

static public URL fileToURL(String sfile) { File file = new File(sfile); String path = file.getAbsolutePath(); String fSep = System.getProperty("file.separator"); if (fSep != null && fSep.length() == 1) path = path.replace(fSep.charAt(0), '/'); if (path.length() > 0 && path.charAt(0) != '/') path = '/' + path; try { return new URL("file", null, path); } catch (java.net.MalformedURLException e) { // Can only happen if the file // protocol were not recognized throw new Error("unexpected MalformedURLException"); } } } Creating a Valid XML Document from Java Classes The following Java code shows how generated methods might be used. Here, two row elements are created: emp_row1 and emp_row2. Elements for each column are also created (empno1, ename1, and so on). To build an XML document tree, the various data elements are grouped by assigning them to each row element as tree nodes. Each row element is then added as a node to the document root element EMPLIST. In this example, classes generated by the class generator are in uppercase: import oracle.xml.classgen.*; import oracle.xml.parser.*; public class CreateEmployees { public static void main (String args[]) { try { EMP EMPLIST = new EMP(); DTD dtd = EMPLIST.getDTDNode(); // get static from base document // New employee emp_row1 EMP_ROW emp_row1 = new EMP_ROW(1); // create row and set ROWNO

Page 15: Using XML in Oracle Database Applicationssaleemsyed4u.weebly.com/uploads/8/5/7/0/8570245/xml.pdf · Using XML in Oracle Database Applications Part 1: About XML This document presents

EMPNO empno1 = new EMPNO("7654"); ENAME ename1 = new ENAME("MARTIN"); JOB job1 = new JOB("SALESMAN"); MGR mgr1 = new MGR("7698"); HIREDATE hiredate1 = new HIREDATE("1981-09-28 00:00:00.0"); SAL sal1= new SAL("1250"); COMM comm1= new COMM("1400"); DEPTNO deptno1 = new DEPTNO("30"); // New employee emp_row2 EMP_ROW emp_row2 = new EMP_ROW(2); // create row and set ROWNO EMPNO empno2 = new EMPNO("7788"); ENAME ename2 = new ENAME("SCOTT "); JOB job2 = new JOB("ANALYST "); MGR mgr1 = new MGR("7566"); HIREDATE hiredate2 = new HIREDATE("1987-04-19 00:00:00.0"); SAL sal2= new SAL("3000"); COMM comm2= new COMM(""); DEPTNO deptno2 = new DEPTNO("20"); emp_row1.addnode(empno1); // Add data as tree nodes to emp_row1 emp_row1.addnode(ename1); ... emp_row2.addnode(empno2); // Add data as tree nodes to emp_row2 emp_row2.addnode(ename2); ... EMPLIST.addNode(emp1); // Add emp_row1 as tree node to // EMPLIST doc root EMPLIST.addNode(emp2); // Add emp_row2 as tree node to // EMPLIST doc root EMPLIST.validateContent(); EMPLIST.print(System.out); } catch (Exception e) { System.out.println(e.toString()); e.printStackTrace(); } } } XML Document Created by Java Application

Page 16: Using XML in Oracle Database Applicationssaleemsyed4u.weebly.com/uploads/8/5/7/0/8570245/xml.pdf · Using XML in Oracle Database Applications Part 1: About XML This document presents

The Java application above creates an XML document similar to the following: <?xml version="1.0"?> <!DOCTYPE EMP SYSTEM "employee.dtd"> <EMP> <EMP_ROW ROWNO = "1"> <EMPNO>7654</EMPNO> <ENAME>MARTIN</ENAME> <JOB>SALESMAN</JOB> <MGR>7698</MGR> <HIREDATE>1981-09-28 00:00:00.0</HIREDATE> <SAL>1250</SAL> <COMM>1400</COMM> <DEPTNO>30</DEPTNO> /EMP_ROW> <EMP_ROW ROWNO = "2"> <EMPNO>7788</EMPNO> <ENAME>SCOTT</ENAME> <JOB>ANALYST</JOB> <MGR>7566</MGR> <HIREDATE>1987-04-19 00:00:00.0</HIREDATE> <SAL>3000</SAL> <COMM></COMM> <DEPTNO>20</DEPTNO> </EMP_ROW> </EMP> XML SQL Utility for Java The XML SQL Utility for Java consists of a set of Java classes that: pass a query to the database and generate an XML document (text or DOM) from the results write XML data to a database table Generating XML from Query Results As shown in the following figure, the XML SQL Utility can process SQL queries and return the results as an XML document.

Page 17: Using XML in Oracle Database Applicationssaleemsyed4u.weebly.com/uploads/8/5/7/0/8570245/xml.pdf · Using XML in Oracle Database Applications Part 1: About XML This document presents

The structure of the resulting XML document is based on the internal structure of the database schema that returns the query results. Columns are mapped to top level elements. Scalar values are mapped to elements with text-only content. Object types are mapped to elements with attributes appearing as sub-elements. Collections are mapped to lists of elements. Object references and referential constraints are mapped to XML IDREFs. The utility can generate either a string representation of the XML document, or an in-memory XML DOM tree of elements. If you are returning the XML document to a requester, the string representation is best. You should use the DOM representation if you are going to operate on the XML programmatically, for example, transform it using the XSLT Processor or use DOM methods to search or modify the XML in some way. You can also use the XML SQL Utility to generate a DTD based on the schema of the underlying table being queried. You can use the generated DTD as input to the XML Class Generator for Java, which will generate a set of classes based on the DTD elements. You can then write Java code that use these classes to generate the infrastructure behind a web-based form. Based on this infrastructure, the web form will capture user data and create an XML document compatible with the database schema. This data can then be written directly to the corresponding database table or object view without further processing. For more information about this approach, see Exchanging Data Among Applications. Example: Generating XML from Query Results The following is simple example of using the XML SQL Utility to create an XML document from a query. Submitting the following query to the utility: SELECT EMPNO, ENAME FROM EMP WHERE EMPNO = 7654; generates the following XML document:

Page 18: Using XML in Oracle Database Applicationssaleemsyed4u.weebly.com/uploads/8/5/7/0/8570245/xml.pdf · Using XML in Oracle Database Applications Part 1: About XML This document presents

<?xml version="1.0"?> <ROWSET> <ROW id="1"> <EMPNO>7654</EMPNO> <ENAME>MARTIN</ENAME> </ROW> </ROWSET> Note the format of the XML document. By default, ROWSET is the element name of the XML document element. ROW is the element name for each row in the query result. Data such as EMPNO and ENAME are also represented as elements nested within the ROW node. In general, data is represented as elements and attributes are used to constrain the data where needed. Should an application require a different set of tags, an XSL stylesheet can perform the transformation dynamically. Example: Generating XML from Query Results and Structuring the Data Using the XML SQL Utility's API, you can also constrain the data presented in the XML document. For example, you can specify things like the maximum number of rows to return, the number of rows to be skipped, what XSL stylesheet to use, among others. The following Java code queries the database and constructs an XML file containing the results. The query is a simple select EMPNO, ENAME from EMP: import java.sql.*; import java.math.*; import oracle.xml.sql.query.*; import oracle.jdbc.*; import oracle.jdbc.driver.*; public class xmlquerydb { public static void main(String args[]) throws SQLException { String tabName = "emp"; String user = "scott/tiger"; DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); //initiate a JDBC connection Connection conn = DriverManager.getConnection("jdbc:oracle:oci8:"+user+"@"); // initialize the OracleXMLQuery OracleXMLQuery qry = new OracleXMLQuery(conn,"select EMPNO, ENAME from "+tabName );

Page 19: Using XML in Oracle Database Applicationssaleemsyed4u.weebly.com/uploads/8/5/7/0/8570245/xml.pdf · Using XML in Oracle Database Applications Part 1: About XML This document presents

// structure the generated XML document qry.setMaxRows(2); // set the maximum number of rows to be returned qry.setRowsetTag("ROOTDOC"); // set the root document tag qry.setRowTag("DBROW"); // sets the row separator tag qry.setStyleSheet("emp.xsl"); // sets the stylesheet // get the XML document in string format String xmlString = qry.getXMLString(); // print out the XML document System.out.println(" OUTPUT IS:\n"+xmlString); } } The resulting XML file returns the first two rows found in the EMP table: <?xml version="1.0"?> <ROOTDOC> <DBROW id="1"> <EMPNO>7876</EMPNO> <ENAME>ADAMS</ENAME> </DBROW> <DBROW id="2"> <EMPNO>7499</EMPNO> <ENAME>ALLEN</ENAME> </DBROW> </ROOTDOC> Writing XML to a Database Table As shown in then following figure, you can use the XML SQL Utility to write XML data to an Oracle8i object-relational database table.

Storing an XML document in an Oracle8i preserves the structure of the document. Element tag names are mapped to column names in the table. Elements with text-only content are mapped to scalar columns, and elements containing sub-elements are mapped to object types. Lists of elements are mapped to collections. Unstructured data like textual comments or descriptions cannot be mapped to underlying database tables, so this kind of data should be stored as a CLOB in the database. See Oracle8i and interMedia for more information.

Page 20: Using XML in Oracle Database Applicationssaleemsyed4u.weebly.com/uploads/8/5/7/0/8570245/xml.pdf · Using XML in Oracle Database Applications Part 1: About XML This document presents

Example: Writing XML to a Database Table The following Java code inserts the data from the XML file emp.xml into the EMP table. This example assumes the XML document already conforms to the structure of the EMP table. import oracle.xml.sql.dml.*; import java.sql.*; import oracle.jdbc.driver.*; import oracle.jdbc.*; import java.net.*; public class xmlwritedb { public static void main(String args[]) throws SQLException { String tabName = "EMP"; // Table into which to insert XML data String fileName = "emp.xml"; // XML document filename DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); // Initialize a JDBC connection Connection conn = DriverManager.getConnection("jdbc:oracle:oci8:scott/tiger@"); // Insert XML data from file (filename) into // database table (tabName) OracleXMLSave save = new OracleXMLSave(conn, tabName); URL url = save.createURL(fileName); int rowCount = save.insertXML(url); System.out.println(" successfully inserted "+rowCount+ " rows into "+ tabName); conn.close(); } } Note, that if you want to write an XML document to a database table, but the XML data does not match the underlying table structure, you need to transform the XML document before writing it to the database. For techniques on doing this, see Exchanging Data Among Applications. XSQL Servlet The XSQL Servlet is a tool that processes SQL queries and outputs the result set as XML. This processor is implemented as a Java servlet and takes as its input an XML file

Page 21: Using XML in Oracle Database Applicationssaleemsyed4u.weebly.com/uploads/8/5/7/0/8570245/xml.pdf · Using XML in Oracle Database Applications Part 1: About XML This document presents

containing embedded SQL queries. It uses the XML Parser for Java and the XML SQL Utility to perform many of its operations. You can run this servlet in any web server that supports Java servlets. The following figure shows how data flows from a client, to the servlet, and back to the client. The sequence of events is as follows: 1.The user enters a URL through a browser, which is interpreted and passed to the XSQL Servlet through a Java Web Server. The URL contains the name of the target XSQL file (.xsql) and optionally, parameters, such as values and an XSL stylesheet name. Alternatively, the user can invoke the XSQL Servlet from the command line, bypassing the browser and Java web server. 2.The servlet passes the XSQL file to the XML Parser for Java, which parses the XML and creates an API for accessing the XML contents. 3.The page processor component of the servlet uses the API to pass XML parameters and SQL statements (found between <query></query> tags) to the XML SQL Utility. The page processor also passes any XSL processing statements to the XSLT Processor. 4.The XML SQL Utility sends the SQL queries to the underlying Oracle8i database, which returns the query results to the utility. 5.The XML SQL Utility returns the query results to the XSLT Processor as XML formatted text. The results are embedded in the XML file in the same location as the original <query> tags. 6.If desired, the query results and any other XML data are transformed by the XSLT Processor using a specified XSL stylesheet. The data can be transformed HTML or any other format defined by the stylesheet. The XSLT Processor can selectively apply different stylesheets based on the type of client that made the original URL request. This HTTP_USER_AGENT information is obtained from the client through an HTTP request. 7.The XSLT Processor passes the completed document back to the client browser for presentation to the user.

Page 22: Using XML in Oracle Database Applicationssaleemsyed4u.weebly.com/uploads/8/5/7/0/8570245/xml.pdf · Using XML in Oracle Database Applications Part 1: About XML This document presents

Example: XSQL Servlet The following is a simple XSQL file that queries an employee table EMP. The default behavior of the query is to return all employee rows in the table. Optionally, you can narrow the search by adding a find= URL parameter when calling the XSQL servlet from the browser. For example, specifying the letter 'T' as the find value will return only those rows whose ENAME contains the letter T. Also, you can sort the returned rows by specifying a sort= URL parameter. For example, specifying EMPNO will sort the rows by employee number. <?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="rowcol.xsl"?> <query connection="demo" find="%" sort="ENAME" null-indicator="yes" > SELECT * FROM EMP WHERE ENAME LIKE '%{@find}%' ORDER BY {@sort}

Page 23: Using XML in Oracle Database Applicationssaleemsyed4u.weebly.com/uploads/8/5/7/0/8570245/xml.pdf · Using XML in Oracle Database Applications Part 1: About XML This document presents

</query> The XSQL file also specifies that the returned results should be processed using the XSL stylesheet rowcol.xsl. This stylesheet is as follows. <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <html> <body class="page"> <xsl:apply-templates/> </body> </html> </xsl:template> <xsl:template match="ROWSET"> <center> <table border="0" cellpadding="4"> <xsl:choose> <xsl:when test="ROW"> <!-- present headings: row[1] columns +--> <xsl:for-each select="ROW[1]"> <tr> <xsl:for-each select="*"> <th align="left"> <xsl:attribute name="class"> </xsl:attribute> <xsl:value-of select="name(.)"/> </th> </xsl:for-each> </tr> </xsl:for-each> <xsl:apply-templates/> </xsl:when> <xsl:otherwise> <tr><td>No Matches</td></tr> </xsl:otherwise> </xsl:choose> </table> </center> </xsl:template> <!-- present rows and columns +--> <xsl:template match="ROW"> <tr> <xsl:attribute name="class"> </xsl:attribute>

Page 24: Using XML in Oracle Database Applicationssaleemsyed4u.weebly.com/uploads/8/5/7/0/8570245/xml.pdf · Using XML in Oracle Database Applications Part 1: About XML This document presents

<xsl:for-each select="*"> <td> <xsl:attribute name="class"> </xsl:attribute> <xsl:apply-templates select='.'/> </td> </xsl:for-each> </tr> </xsl:template> </xsl:stylesheet> The figure below shows the HTML page that is generated by the XSQL Servlet using the XSQL file emp.xsql and the rowcol.xsl stylesheet. This servlet was invoked using the following URL: http://localhost/xsql/demo/emp.xsql?find=T&sort=EMPNO

XML Transviewer Java Beans The XML Transviewer Beans are a set of XML components for Java applications or applets. These visual and non-visual Java components can be integrated into Oracle JDeveloper to enable developers to create and deploy XML-based database applications quickly. The following beans are available: DOM Builder Bean XML Source Viewer Bean XML Tree Viewer Bean XSL Transformer Bean DOM Builder Bean The DOM Builder Bean encapsulates the Java XML Parser with a bean interface and extends its functionality to permit asynchronous parsing. By registering a listener, Java applications can parse large or successive documents having control return immediately to the caller.

Page 25: Using XML in Oracle Database Applicationssaleemsyed4u.weebly.com/uploads/8/5/7/0/8570245/xml.pdf · Using XML in Oracle Database Applications Part 1: About XML This document presents

XML Source Viewer Bean The XML Source View Bean improves the viewing of XML and XSL files by color-highlighting XML/XSL syntax. This is usefule when modifying an XML document with an editing application. Easily integrated with the DOM Builder Bean, it allows for pre or post parsing and validation against a specified DTD. XML Tree Viewer Bean The XML Tree View Bean displays a visual view of an XML document, enabling users to easily manipulate the tree with a mouse to hide or view selected branches. XSL Transformer Bean The XSL Transformer Bean enables users to transform an XML document to almost any text-based format including XML, HTML and DDL, by applying an XSL stylesheet. When integrated with other beans, this bean enables an application or user to view the results of transformations immediately. 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.