Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (5.26 MB, 774 trang )
Using XML Parser for Java: DOMParser() Class
XML Parser for Java - DTD Example 1: (NSExample)
]>
xmlns:nsprefix="http://www.oracle.com">
This element inherits the default Namespace of doc.
Using XML Parser for Java: DOMParser() Class
To write DOM based parser applications you can use the following classes:
s
DOMNamespace() class
s
DOMParser() class
s
XMLParser() class
Since DOMParser extends XMLParser, all methods of XMLParser are also available
to DOMParser. Figure 4–4 shows the main steps you need when coding with the
DOMParser() class:
s
Without DTD Input
1.
A new DOMParser() class is called. Available properties to use with this
class are:
*
setValidateMode
*
setPreserveWhiteSpace
*
setDocType
*
setBaseURL
*
showWarnings
XML Parser for Java 4-15
Using XML Parser for Java: DOMParser() Class
2.
The results of 1) are passed to XMLParser.parse() along with the XML
input. The XML input can be a file, a string buffer, or URL.
3.
Use the XMLParser.getDocument() method.
4.
Optionally, you can apply other DOM methods such as:
*
print()
*
DOMNamespace() methods
5.
6.
s
The Parser outputs the DOM tree XML (parsed) document.
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.
The results of 1) are passed to XMLParser.parseDTD() method along
with the DTD input.
3.
XMLParser.getDocumentType() method then sends the resulting DTD
object back to the new DOMParser() and the process continues until the
DTD has been applied.
The example, "XML Parser for Java Example 1: Using the Parser and DOM API",
shows hoe to use DOMParser() class.
4-16
Oracle9i XML Developer’s Kits Guide - XDK
Using XML Parser for Java: DOMParser() Class
Figure 4–4 XML Parser for Java: DOMParser()
XDK for Java: XML Parser for Java — DOM Parser()
new
DOMParser()
Available properties:
· setValidationMode
[default = not]
· setPreserveWhiteSpace
[default = not]
· setDocType
[if input type is a DTD]
· setBaseURL
[refers other locations to
base location if reading
from outside source ]
· showWarnings
file, string
buffer, or URL
xml input
DTD input
XMLParser.
parse()
XMLParser.
parseDTD()
XMLParser.
getDocument
XMLParser.
getDocumentType()
Apply other
DOM methods
DOMParser.
reset()
DTD
object
Typically Node
class methods
To print, use the
print method.
This is a
nonstandard
DOM method
DOM
document
XML Parser for Java Example 1: Using the Parser and DOM API
The examples represent the way we write code so it is required to present the
examples with Java coding standards (like all imports expanded), with
documentation headers before the methods, and so on.
//
//
//
//
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.
XML Parser for Java 4-17
Using XML Parser for Java: DOMParser() Class
//
import
import
import
import
java.io.*;
java.net.*;
org.w3c.dom.*;
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(DTD_validation);
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
4-18
Oracle9i XML Developer’s Kits Guide - XDK
Using XML Parser for Java: DOMParser() Class
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
{
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
{
XML Parser for Java 4-19
Using XML Parser for Java: DOMParser() Class
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;
}
}
4-20
Oracle9i XML Developer’s Kits Guide - XDK
Using XML Parser for Java: DOMParser() Class
Comments on DOMParser() Example 1
See also Figure 4–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(DTD_validation);
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 a URL. 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:
s
Node class methods:
*
*
getAttributes()
*
getNodeName()
*
s
getElementsByTagName()
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.
XML Parser for Java 4-21
Using XML Parser for Java: DOMNamespace() Class
Using XML Parser for Java: DOMNamespace() Class
Figure 4–3 illustrates the main processes involved when parsing an XML document
using the DOM interface. The DOMNamespace() method is applied in the parser
process at the “bubble” that states “Apply other DOM methods”. The following
example illustrates how to use DOMNamespace():
s
"XML Parser for Java Example 2: Parsing a URL — DOMNamespace.java"
XML Parser for Java Example 2: Parsing a URL — DOMNamespace.java
//
//
//
//
//
This file demonstates a simple use of the parser and Namespace
extensions to the DOM APIs.
The XML file given to the application is parsed and the
elements and attributes in the document are printed.
import java.io.*;
import java.net.*;
import oracle.xml.parser.v2.DOMParser;
import org.w3c.dom.*;
import org.w3c.dom.Node;
// Extensions to DOM Interfaces for Namespace support.
import oracle.xml.parser.v2.XMLElement;
import oracle.xml.parser.v2.XMLAttr;
public class DOMNamespace
{
static public void main(String[] argv)
{
try
{
if (argv.length != 1)
{
// Must pass in the name of the XML file.
System.err.println("Usage: DOMNamespace filename");
System.exit(1);
}
// Get an instance of the parser
Class cls = Class.forName("oracle.xml.parser.v2.DOMParser");
4-22
Oracle9i XML Developer’s Kits Guide - XDK
Using XML Parser for Java: DOMNamespace() Class
DOMParser parser = (DOMParser)cls.newInstance();
// Generate a URL from the filename.
URL url = createURL(argv[0]);
// Parse the document.
parser.parse(url);
// Obtain the document.
Document doc = parser.getDocument();
// Print document elements
printElements(doc);
// Print document element attributes
System.out.println("The attributes of each element are: ");
printElementAttributes(doc);
}
catch (Exception e)
{
System.out.println(e.toString());
}
}
static void printElements(Document doc)
{
NodeList nl = doc.getElementsByTagName("*");
XMLElement nsElement;
String
String
String
String
qName;
localName;
nsName;
expName;
System.out.println("The elements are: ");
for (int i=0; i < nl.getLength(); i++)
{
nsElement = (XMLElement)nl.item(i);
// Use the methods getQualifiedName(), getLocalName(), getNamespace()
// and getExpandedName() in NSName interface to get Namespace
// information.
qName = nsElement.getQualifiedName();
System.out.println(" ELEMENT Qualified Name:" + qName);
XML Parser for Java 4-23