Oracle8i Application Developer's Guide - XML Release 3 (8.1.7) Part Number A86030-01 |
Library | Service | Contents | Index

Using XML Parser for Java, 21 of 22

## General XML Parser Related Questions

### How the XML Parser Works

#### Question

What does an XML Parser do?

#### Answer

The parser accepts any XML document giving you a tree-based API (DOM) to access or modify the document's elements and attributes as well as an event-API (SAX) that provides a listener to be registered and report specific elements or attributes and other document events.

### Converting XML Files to HTML Files

#### Question

How do I convert XML files into HTML files?

#### Answer

You need to create an XSL stylesheet to render your XML into HTML. You can start with an HTML document in your desired format and populated with dummy data. Then you can replace this data with the XSL-T commands that will populate the HTML with data from the XML document completing your stylesheet.

### Validating Against XML Schema

#### Question

Does the XML Parser v2 validate against an XML Schema ?

#### Answer

It supports both validating and non-validating modes. XML Schema is still under the development W3C XML Schema committee. We will support it as soon as it becomes stable. Currently, our parser supports validating and non-validating DTDs.

### Including Binary Data in an XML Document

#### Question

How do I include binary data in an XML document?

#### Answer

There is no way to directly include binary data within the document; however, there are two ways to work around this:

- Binary data could be referenced as an external unparsed entity that resided in a different file.

- Binary data can be uuencoded (meaning converting binary data into ASCII data) and be included in a CDATA section. The limitation on the encoding technique is to ensure that it only produces legal characters for the CDATA section.

### What is XML Schema?

#### Question

What is the XML Schema?

#### Answer

XML Schema is a W3C XML standards effort to bring the concept of data types to XML documents and in the process replace the syntax of DTDs to one based on XML. For more details, check out http://www.w3.org/TR/xmlschema-1/ and http://www.w3.org/TR/xmlschema-2/.

### Oracle's Participation in Defining the XML/SQL Standard

#### Question

Does Oracle participate in defining the XML/XSL standard?

#### Answer

Oracle has representatives participating actively in the following 3C Working Groups related to XML/XSL: XML Schema, XML Query, XSL, XLink/XPointer, XML Infoset, DOM and XML Core.

### XDK Version Numbers

#### Question

How do I determine the version number of the XDK toolkit that I downloaded?

#### Answer

You can find out the full version number by looking at the readme.html file included in the archive and linked off of the Release Notes page.

### Inserting <, >, >= and <= in XML Documents

#### Question

How do I insert these characters in the XML documents: >,<,>=, and <=?

#### Answer

You need to use the entities &lt; for < and &gt; for >.

### Are Namespace and Schema Supported

#### Question

Is support for Namespaces and Schema included?

#### Answer

The current XML parsers support Namespaces. Schema support will be included in a future release.

### Using JDK 1.1.x with XML Parser for Java v2

#### Question

Can I use JDK 1.1.x with XML Parser v2 for Java?

#### Answer

v2 of XML Parser for Java has nothing to do with Java2. It is simply a designation that indicates that it is not backwards compatible with the v1 Parser and that it includes XSLT support. The v2 parser will work fine with JDK 1.1.x.

### Sorting the Result on the Page

#### Question

I have a set of records say 100, I am showing 10 at a time, now on each column name I have made a link, on the click of the same, I want to sort the data in the page alone, based on that column. How to go about it?

#### Answer

It depends on how you are going about. If you are writing for IE5 alone and receiving XML data, you could just use MS's XSL to sort data in a page.If you are writing for other browser and browsers are getting data as HTML, then you have to have a sort parameter in XSQL script and use it in ORDER BY clause. Just passed it along with skip-rows parameter.

### Is Oracle8i Needed to Run XML Parser for Java?

#### Question

Do I need Oracle8i to run the XML Parser for Java?

#### Answer

XML Parser for Java can be used with any of the supported version JavaVMs. The only difference with 8i is that you can load it into the database and use JServer, which is an internal JVM. For other database versions or servers, you simply run it in an external JVM and as necessary connect to a database through JDBC.

### Dynamically Setting the Encoding in an XML File

#### Question

Is it possible to dynamically set the encodings in the XML file?

#### Answer

No, you need to include the proper encoding declaration in your document as per the specification. You cannot use setEncoding() to set the encoding for you input document. SetEncoding() is used with oracle.xml.parser.v2.XMLDocument to set the correct encoding for the printing.

### Parsing a String

#### Question

How do I parse a string?

#### Answer

We do not currently have any method that can directly parse an XML document contained within a String. You would need to convert the String into an InputStream or InputSource before parsing. An easy way is to create a ByteArrayInputStream using the bytes in the String.

### Displaying an XML Document

#### Question

How do I display my XML document?

#### Answer

If you are using IE5 as your browser you can display the XML document directly. Otherwise, you can use our XSL-T Processor in v2 of the parser to create the HTML document using an XSL Stylesheet. The Oracle XML Transviewer bean also allows you to view your XML document.

### System.out.primtln() and Special Characters

#### Question

I am having problems using System.out.println() with special character encoding.

#### Answer

You can't use System.out.println(). You need to use an output stream which is encoding aware (Ex.OutputStreamWriter). You can construct an OutputStreamWriter and use the write(char[ ], int, int) method to print.

    /* Example */
    OutputStreamWriter out = new OutputStreamWriter
    (System.out, "8859_1");
    /* Java enc string for ISO8859-1*/

### Obtaining Ampersand from Character Data

#### Question

How do I to get ampersand from character data?

#### Answer

You cannot have "raw" ampersands in XML data. You need to use the entity, &amp; instead. This is defined in the XML standard.

### Parsing XML from Data of Type String

#### Question

How do I parse XML from data of type String?

#### Answer

Check out the following example:

    /* xmlDoc is a String of xml */
    byte aByteArr [] = xmlDoc.getBytes();
    ByteArrayInputStream bais = new ByteArrayInputStream (aByteArr, 0,
    aByteArr.length);
    domParser.parse(bais);

### Extracting Data from XML Document into a String

#### Question

How do I extract data from an XML document into type String?

#### Answer

Here is an example to do that:

    XMLDocument Your Document;
    /* Parse and Make Mods */
    :
    StringWriter sw = new StringWriter();
    PrintWriter  pw = new PrintWriter(sw);
    YourDocument.print(pw);
    String YourDocInString = sw.toString();

### Disabling Output Escaping

#### Question

Does XML Parser for Java support Disabling Output Escaping?

#### Answer

Yes, since version 2.022, the parser provides an option to xsl:text to disable output escaping.

### Using the XML Parser for Java with Oracle 8.0.5

#### Question

Is the XML Parser for Java only available for use with Oracle 8i? Is it possible to use with Oracle 8.05

#### Answer

The XML Parser for Java can be used with any of the supported version JavaVMs. The only difference with Oracle8i is that you can load it into the database and use JServer which is an internal VM. For 8.0.5 you simple run it externally and connect through JDBC.

### Delimiting Multiple XML Documents

#### Question

We need to be able to read (and separate) several XML documents as a single string. One solution would be to delimit these documents using some (programatically generated) special character that we know for sure can never occur inside an xml document. The individual documents can then be easily tokenized and extracted/parsed as required.

Has any one else done this before? Any suggestions for what character can be used as the delimiter (for instance can characters in the range #x0-#x8 ever occur inside an xml document?)

#### Answer

As far as legality is concerned and you limit it to 8-bit, #x0-#x8; #xB, #xC, #xE, and #xF are not legal. HOWEVER this assumes that you preprocess the doc and not depend upon exceptions as not ALL parsers reject ALL illegal characters.

Element, which you then append to the Document.

### XML and Entity-references: XML Parser for Java

#### Question

1. The XML-parser for Java does not expand entity references,such as &[whatever], instead all values are null. How can I fix this?

2. It seems you cannot have international character (such as swedish characters, ...,,÷) as values for internal entities. How does one solve this problem?

#### Answer

1. You probably have a simple error defining/using your entities since we've a number of regression tests that handle entity references fine. A simple example is: ]> Alpha, then &status

2. What do you set your character set encoding to be?

### Can I Break up and Store an XML Document without a DDL Insert?

#### Question

1. We would like to break apart an arbitrary XML document and store it in the database without creating a DDL to insert. Is this possible?

2. And as for querying, is it possible to perform hierarchical searches across XML documents?

#### Answer

1. No this is not possible. Either the schema must already exist or and XSL stylesheet to create the DDL from the XML must exist.

2. From Oracle8i Release 8.1.6 interMedia Text can do this.

### Merging XML Documents

#### Question

How can I merge two XML Documents?

#### Answer

This is not possible with the current DOM specification. DOM2 specification may address this.

You can use a DOM-approach or an XSL-T-based approach to accomplish this. If you use DOM, then you'll have to remove the node from one document before you append it into the other document to avoid ownership errors.

Here's an example of the XSL-based approach. Assume your two XML source files are:

demo1.xml

    <messages>
      <msg>
        <key>AAA</key>
        <num>01001</num>
      </msg>
      <msg>
        <key>BBB</key>
        <num>01011</num>
      </msg>
    </messages>

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

Here is a stylesheet the "joins" demo1.xml to demo2.xml based on matching the "<key>" values.

demomerge.xsl

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>
    <xsl:variable name="doc2" select="document('demo2.xml')"/>
      <xsl:template match="@*|node()">
        <xsl:copy>
          <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
      </xsl:template>
    <xsl:template match="msg">
        <xsl:copy>
          <xsl:apply-templates select="@*|node()"/>
          <text><xsl:value-of select="$doc2/messages/msg[key=current()/key]/text"/>
    </text>
        </xsl:copy>
    </xsl:template>
    </xsl:stylesheet>

If you use the command-line "`oraxsl`" to test this out, you would do:

    $ oraxsl demo1.xml demomerge.xsl

And you'll get the merged result of:

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

Obviously not as efficient for larger-sized files as an equivalent database "join" between two tables, but this illustrates the technique if you only have XML files to work with.Error: Cannot Find Class

### Getting the Value of a Tag

#### Question

I am using SAX to parse an XML document. How I can get the value of a particular tag? For example, Java. How do I get the value for title? I know there are startElement, endElement, and characters methods.

#### Answer

During a SAX parse the value of an element will be the concatenation of the characters reported from after startElement to before the corresponding endElement is called.

### Granting JAVASYSPRIV to User

#### Question

We are using Oracle XML Parser for Java on NT 4.0. When we are parsing an XML document with an external DTD we get the following error:

    <!DOCTYPE listsamplereceipt SYSTEM
    "file:/E:/ORACLE/utl_file_dir/dadm/ae.dtd">
    java.lang.SecurityExceptionat
    oracle.aurora.rdbms.SecurityManagerImpl.checkFile(SecurityManagerImpl.java)at
    oracle.aurora.rdbms.SecurityManagerImpl.checkRead(SecurityManagerImpl.java)at
    java.io.FileInputStream.<init>(FileInputStream.java)at
    java.io.FileInputStream.<init>(FileInputStream.java)at
    sun.net.www.MimeTable.load(MimeTable.java)at
    sun.net.www.MimeTable.<init>(MimeTable.java)at
    sun.net.www.MimeTable.getDefaultTable(MimeTable.java)at
    sun.net.www.protocol.file.FileURLConnection.connect(FileURLConnection.java)at
    sun.net.www.protocol.file.FileURLConnection.getInputStream(FileURLConnection.
    java)at
    java.net.URL.openStream(URL.java)at
    oracle.xml.parser.v2.XMLReader.openURL(XMLReader.java:2313)at
    oracle.xml.parser.v2.XMLReader.pushXMLReader(XMLReader.java:176)at
    ...

What is causing this?

#### Answer

Grant the JAVASYSPRIV role to your user running this code to allow it to open the external file/URL.

### Including an External XML File in Another XML File: External Parsed Entities

#### Question

1. I am trying to include an external XML file in another XML file. Does Oracle Parser for Java v1 and v2 support external parsed entities?

2. We are using version 1.0, because that is what is shipped to the customers with release 10.7 and 11.0 of our application. Can you refer me to this, or some other sample code to do this.

   Shouldn't file b.xml be in the format:

       <?xml version="1.0" ?>
       <b>
         <ok/>
       </b>

   Does Oracle XML Parser come with a utility to parse an XML file and see the parsed output?

#### Answer

1. IE 5.0 will parse an XML file and show the parsed output. Just load the file like you would an HTML page.

   The following works, both browsing it in IE5 as well as parsing it with Oracle XML Parser v2. Even though I'm sure it works fine in Oracle XML Parser 1.0, you should be using the latest parser version as it is faster than v1.

   File: a.xml

       <?xml version="1.0" ?>
       <!DOCTYPE a [<!ENTITY b SYSTEM "b.xml">]>
        <a>&b;</a>

   File: b.xml

        <ok/>

   When I browse/parse a.xml I get the following:

       <a>
         <ok/>
       </a>

2. Not strictly. The parsed external entity only needs to be a well-formed fragment. The following program (with xmlparser.jar from v 1.0) in your CLASSPATH shows parsing and printing the parsed document. It's parsing here from a String but the mechanism would be no different for parsing from a file, given it's URL.

       import oracle.xml.parser.*;
       import java.io.*;
       import java.net.*;
       import org.w3c.dom.*;
       import org.xml.sax.*;
       /*
       ** Simple Example of Parsing an XML File from a String
       ** and, if successful, printing the results.
       **
       ** Usage: java ParseXMLFromString <hello><world/></hello>
       */
       public class ParseXMLFromString {
         public static void main( String[] arg ) throws IOException, SAXException {
           String theStringToParse =
              "<?xml version='1.0'?>"+
              "<hello>"+
              "  <world/>"+
              "</hello>";
           XMLDocument theXMLDoc = parseString( theStringToParse );
           // Print the document out to standard out
           theXMLDoc.print(System.out);
         }
         public static XMLDocument parseString( String xmlString ) throws
          IOException, SAXException {
          XMLDocument theXMLDoc     = null;
           // Create an oracle.xml.parser.v2.DOMParser to parse the document.
           XMLParser theParser = new XMLParser();
           // Open an input stream on the string
           ByteArrayInputStream theStream =
                new ByteArrayInputStream( xmlString.getBytes() );
           // Set the parser to work in non-Validating mode
           theParser.setValidationMode(false);
           try {
             // Parse the document from the InputStream
             theParser.parse( theStream );
             // Get the parsed XML Document from the parser
             theXMLDoc = theParser.getDocument();
           }
           catch (SAXParseException s) {
             System.out.println(xmlError(s));
             throw s;
           }
           return theXMLDoc;
         }
         private static String xmlError(SAXParseException s) {
            int lineNum = s.getLineNumber();
            int  colNum = s.getColumnNumber();
            String file = s.getSystemId();
            String  err = s.getMessage();
            return "XML parse error in file " + file +
                   "\n" + "at line " + lineNum + ", character " + colNum +
                   "\n" + err;
         }
       }

### OraXSL Parser

#### Question

From where I can download oracle.xml.parser.v2.OraXSL?

#### Answer

It's part of our integrated XML Parser for Java V2 release. Our XML Parser, DOM, XPath implementation, and XSLT engine are nicely integrated into a single, cooperating package. http://technet.oracle.com/tech/xml/parser_java2/

| Copyright © 1996-2000, Oracle Corporation. All Rights Reserved. |
Library | Service | Contents | Index