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

Using XML Parser for Java, 6 of 22

## Using XML Parser for Java: DOMParser() Class

To write DOM based parser applications you can implement the following classes:

- DOMNamespace class

- DOMParser() class

- XMLParser() class

Figure 17-4 shows the main steps you need when coding with the DOMParser() class:

- Without DTD Input

  1. A new DOMParser() class is called. The available properties to apply to this class are:

     - setValidateMode

     - setPreserveWhiteSpace

     - setDocType

     - setBaseURL

     - showWarnings

  2. This is applied to XMLParser.parse() along with the XML input. The XML input can be a file, string buffer, or URL.

  3. The XMLParser.getDocument() method is implemented.

  4. Optionally, you can apply other DOM methods such as:

     - print()

     - DOMNamespace() methods

  5. The Parser outputs the DOM tree XML (parsed) document .

  6. Optionally, use DOMParser.reset() to clean up any internal data structures, once the Parser has finished building the DOM tree.

- With a DTD Input

  1. A new DOMParser() class is called. The available properties to apply to this class are:

     - setValidateMode

     - setPreserveWhiteSpace

     - setDocType

     - setBaseURL

     - showWarnings

  2. This is applied to XMLParser.parseDTD() method along with the DTD input.

  3. The XMLParser.getDocumentType() method then sends the resulting DTD object back to the new DOMParser() and the process continues until the DTD has been applied.

Using the DOMParser() class is illustrated with the following example:

- "XML Parser for Java Example 1: Using the Parser and DOM API (DomSample.java)"

#### Figure 17-4 XML Parser for Java: DOMParser()

### XML Parser for Java Example 1: Using the Parser and DOM API (DomSample.java)

    // This file demonstates a simple use of the parser and DOM API.
    // The XML file given to the application is parsed.
    // The elements and attributes in the document are printed.
    // This demonstrates setting the parser options.
    //

    import java.io.*;
    import java.net.*;
    import org.w3c.dom.*;
    import org.w3c.dom.Node;

    import oracle.xml.parser.v2.*;

    public class DOMSample
    {
       static public void main(String[] argv)
       {
          try
          {
             if (argv.length != 1)
             {
                // Must pass in the name of the XML file.
                System.err.println("Usage: java DOMSample filename");
                System.exit(1);
             }

             // Get an instance of the parser
             DOMParser parser = new DOMParser();

    	 // Generate a URL from the filename.
    	 URL url = createURL(argv[0]);

             // Set various parser options: validation on,
             // warnings shown, error stream set to stderr.
             parser.setErrorStream(System.err);
             parser.setValidationMode(true);
             parser.showWarnings(true);

    	 // Parse the document.
             parser.parse(url);

             // Obtain the document.
             XMLDocument doc = parser.getDocument();

             // Print document elements
             System.out.print("The elements are: ");
             printElements(doc);

             // Print document element attributes
             System.out.println("The attributes of each element are: ");
             printElementAttributes(doc);
             parser.reset();
          }
          catch (Exception e)
          {
             System.out.println(e.toString());
          }
       }

       static void printElements(Document doc)
       {
          NodeList nl = doc.getElementsByTagName("*");
          Node n;

          for (int i=0; i<nl.getLength(); i++)
          {
             n = nl.item(i);
             System.out.print(n.getNodeName() + " ");
          }

          System.out.println();
       }

       static void printElementAttributes(Document doc)
       {
          NodeList nl = doc.getElementsByTagName("*");
          Element e;
          Node n;
          NamedNodeMap nnm;

          String attrname;
          String attrval;
          int i, len;

          len = nl.getLength();
          for (int j=0; j < len; j++)
          {
             e = (Element)nl.item(j);
             System.out.println(e.getTagName() + ":");
             nnm = e.getAttributes();
             if (nnm != null)
             {
                for (i=0; i<nnm.getLength(); i++)
                {
                   n = nnm.item(i);
                   attrname = n.getNodeName();
                   attrval = n.getNodeValue();
                   System.out.print(" " + attrname + " = " + attrval);
                }
             }
             System.out.println();
          }
       }

       static URL createURL(String fileName)
       {
          URL url = null;
          try
          {
             url = new URL(fileName);
          }
          catch (MalformedURLException ex)
          {
             File f = new File(fileName);
             try
             {
                String path = f.getAbsolutePath();
                String fs = System.getProperty("file.separator");
                if (fs.length() == 1)
                {
                   char sep = fs.charAt(0);
                   if (sep != '/')
                      path = path.replace(sep, '/');
                   if (path.charAt(0) != '/')
                      path = '/' + path;
                }
                path = "file://" + path;
                url = new URL(path);
             }
             catch (MalformedURLException e)
             {
                System.out.println("Cannot create url for: " + fileName);
                System.exit(0);
             }
          }
          return url;
       }
    }

### Comments on DOMParser() Example 1

See also Figure 17-4. The following provides comments for Example 1:

1. Declare a new DOMParser(). In Example 1, see the line:

       DOMParser parser = new DOMParser();

   This class has several properties you can use. Here the example uses:

       parser.setErrorStream(System.err);
       parser.setValidationMode(true);
       parser.showWarnings(true);

2. The XML input is a URL as declared by:

       URL url = createURL(argv[0])

3. The XML document is input as aURL. This is parsed using parser.parse():

        parser.parse(url);

4. Gets the document:

       XMLDocument doc = parser.getDocument();

5. Applies other DOM methods. In this case:

   - Node class methods:

     - getElementsByTagName()

     - getAttributes()

     - getNodeName()

     - getNodeValue()

   - Method, createURL() to convert the string name into a URL.

6. parser.reset() is called to clean up any data structure created during the parse process, after the DOM tree has been created. Note that this is a new method with this release.

7. Generates the DOM tree (parsed XML) document for further processing by your application.

   Note: No DTD input is shown in Example 1.

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