1. Trang chủ >
  2. Công Nghệ Thông Tin >
  3. Kỹ thuật lập trình >

XML Parser for Java Example 3: Using the Parser and SAX API (SAXSample.java)

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: SAXParser() Class



{

// Must pass in the name of the XML file.

System.err.println("Usage: SAXSample filename");

System.exit(1);

}

// (1) Create a new handler for the parser

SAXSample sample = new SAXSample();

// (2) Get an instance of the parser

Parser parser = new SAXParser();

// (3) Set Handlers in the parser

parser.setDocumentHandler(sample);

parser.setEntityResolver(sample);

parser.setDTDHandler(sample);

parser.setErrorHandler(sample);

// (4) Convert file to URL and parse

try

{

parser.parse(fileToURL(new File(argv[0])).toString());

}

catch (SAXParseException e)

{

System.out.println(e.getMessage());

}

catch (SAXException e)

{

System.out.println(e.getMessage());

}

}

catch (Exception e)

{

System.out.println(e.toString());

}

}

static URL fileToURL(File file)

{

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;



XML Parser for Java 4-29



Using XML Parser for Java: SAXParser() Class



try

{

return new URL("file", null, path);

}

catch (java.net.MalformedURLException e)

{

throw new Error("unexpected MalformedURLException");

}

}

//////////////////////////////////////////////////////////////////////

// (5) Sample implementation of DocumentHandler interface.

//////////////////////////////////////////////////////////////////////

public void setDocumentLocator (Locator locator)

{

System.out.println("SetDocumentLocator:");

this.locator = locator;

}

public void startDocument()

{

System.out.println("StartDocument");

}

public void endDocument() throws SAXException

{

System.out.println("EndDocument");

}

public void startElement(String name, AttributeList atts)

throws SAXException

{

System.out.println("StartElement:"+name);

for (int i=0;i
{

String aname = atts.getName(i);

String type = atts.getType(i);

String value = atts.getValue(i);

System.out.println("



"+aname+"("+type+")"+"="+value);



}

}

public void endElement(String name) throws SAXException

{



4-30



Oracle9i XML Developer’s Kits Guide - XDK



Using XML Parser for Java: SAXParser() Class



System.out.println("EndElement:"+name);

}

public void characters(char[] cbuf, int start, int len)

{

System.out.print("Characters:");

System.out.println(new String(cbuf,start,len));

}

public void ignorableWhitespace(char[] cbuf, int start, int len)

{

System.out.println("IgnorableWhiteSpace");

}



public void processingInstruction(String target, String data)

throws SAXException

{

System.out.println("ProcessingInstruction:"+target+" "+data);

}

//////////////////////////////////////////////////////////////////////

// (6) Sample implementation of the EntityResolver interface.

//////////////////////////////////////////////////////////////////////

public InputSource resolveEntity (String publicId, String systemId)

throws SAXException

{

System.out.println("ResolveEntity:"+publicId+" "+systemId);

System.out.println("Locator:"+locator.getPublicId()+" "+

locator.getSystemId()+

" "+locator.getLineNumber()+" "+locator.getColumnNumber());

return null;

}

//////////////////////////////////////////////////////////////////////

// (7) Sample implementation of the DTDHandler interface.

//////////////////////////////////////////////////////////////////////

public void notationDecl (String name, String publicId, String systemId)

{

System.out.println("NotationDecl:"+name+" "+publicId+" "+systemId);

}

public void unparsedEntityDecl (String name, String publicId,



XML Parser for Java 4-31



Using XML Parser for Java: SAXParser() Class



String systemId, String notationName)

{

System.out.println("UnparsedEntityDecl:"+name + " "+publicId+" "+

systemId+" "+notationName);

}

//////////////////////////////////////////////////////////////////////

// (8) Sample implementation of the ErrorHandler interface.

//////////////////////////////////////////////////////////////////////

public void warning (SAXParseException e)

throws SAXException

{

System.out.println("Warning:"+e.getMessage());

}

public void error (SAXParseException e)

throws SAXException

{

throw new SAXException(e.getMessage());

}



public void fatalError (SAXParseException e)

throws SAXException

{

System.out.println("Fatal error");

throw new SAXException(e.getMessage());

}

}



XML Parser for Java Example 4: (SAXNamespace.java)

// This file demonstrates a simple use of the Namespace extensions to

// the SAX APIs.

import

import

import

import



org.xml.sax.*;

java.io.*;

java.net.URL;

java.net.MalformedURLException;



// Extensions to the SAX Interfaces for Namespace support.

import oracle.xml.parser.v2.XMLDocumentHandler;

import oracle.xml.parser.v2.DefaultXMLDocumentHandler;

import oracle.xml.parser.v2.NSName;



4-32



Oracle9i XML Developer’s Kits Guide - XDK



Using XML Parser for Java: SAXParser() Class



import oracle.xml.parser.v2.SAXAttrList;

import oracle.xml.parser.v2.SAXParser;

public class SAXNamespace {

static public void main(String[] args) {

String fileName;

//Get the file name

if (args.length == 0)

{

System.err.println("No file Specified!!!");

System.err.println("USAGE: java SAXNamespace ");

return;

}

else

{

fileName = args[0];

}

try {

// Create handlers for the parser

// Use the XMLDocumentHandler interface for namespace support

// instead of org.xml.sax.DocumentHandler

XMLDocumentHandler xmlDocHandler = new XMLDocumentHandlerImpl();

// For all the other interface use the default provided by

// Handler base

HandlerBase defHandler = new HandlerBase();

// Get an instance of the parser

SAXParser parser = new SAXParser();

// Set Handlers in the parser

// Set the DocumentHandler to XMLDocumentHandler

parser.setDocumentHandler(xmlDocHandler);

// Set the other Handler to the defHandler

parser.setErrorHandler(defHandler);

parser.setEntityResolver(defHandler);

parser.setDTDHandler(defHandler);

try

{

parser.parse(fileToURL(new File(fileName)).toString());



XML Parser for Java 4-33



Using XML Parser for Java: SAXParser() Class



}

catch (SAXParseException e)

{

System.err.println(args[0] + ": " + e.getMessage());

}

catch (SAXException e)

{

System.err.println(args[0] + ": " + e.getMessage());

}

}

catch (Exception e)

{

System.err.println(e.toString());

}

}

static public URL fileToURL(File file)

{

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

/* According to the spec this could only happen if the file

/* protocol were not recognized. */

throw new Error("unexpected MalformedURLException");

}

}

private SAXNamespace() throws IOException

{

}

}

/***********************************************************************

Implementation of XMLDocumentHandler interface. Only the new

startElement and endElement interfaces are implemented here. All other

interfaces are implemented in the class HandlerBase.

**********************************************************************/



4-34



Oracle9i XML Developer’s Kits Guide - XDK



Using XML Parser for Java: SAXParser() Class



class XMLDocumentHandlerImpl extends DefaultXMLDocumentHandler

{

public void XMLDocumentHandlerImpl()

{

}



public void startElement(NSName name, SAXAttrList atts) throws SAXException

{

// Use the methods getQualifiedName(), getLocalName(), getNamespace()

// and getExpandedName() in NSName interface to get Namespace

// information.

String qName;

String localName;

String nsName;

String expName;

qName = name.getQualifiedName();

System.out.println("ELEMENT Qualified Name:" + qName);

localName = name.getLocalName();

System.out.println("ELEMENT Local Name

:" + localName);

nsName = name.getNamespace();

System.out.println("ELEMENT Namespace



:" + nsName);



expName = name.getExpandedName();

System.out.println("ELEMENT Expanded Name :" + expName);

for (int i=0; i
{

// Use the methods getQualifiedName(), getLocalName(), getNamespace()

// and getExpandedName() in SAXAttrList interface to get Namespace

// information.

qName = atts.getQualifiedName(i);

localName = atts.getLocalName(i);

nsName = atts.getNamespace(i);

expName = atts.getExpandedName(i);

System.out.println("

System.out.println("

System.out.println("

System.out.println("



ATTRIBUTE

ATTRIBUTE

ATTRIBUTE

ATTRIBUTE



Qualified Name

Local Name

Namespace

Expanded Name



:"

:"

:"

:"



+

+

+

+



qName);

localName);

nsName);

expName);



XML Parser for Java 4-35



Using XML Parser for Java: SAXParser() Class



// You can get the type and value of the attributes either

// by index or by the Qualified Name.

String type = atts.getType(qName);

String value = atts.getValue(qName);

System.out.println(" ATTRIBUTE Type

System.out.println(" ATTRIBUTE Value

System.out.println();



:" + type);

:" + value);



}

}

public void endElement(NSName name) throws SAXException

{

// Use the methods getQualifiedName(), getLocalName(), getNamespace()

// and getExpandedName() in NSName interface to get Namespace

// information.

String expName = name.getExpandedName();

System.out.println("ELEMENT Expanded Name :" + expName);

}

}



oraxml - Oracle XML parser

oraxml is a command-line interface to parse an XML document. It checks for

well-formedness and validity.

To use oraxml ensure the following:

s



s



Your CLASSPATH environment variable is set to point to the

xmlparserv2.jar file that comes with Oracle XML V2 parser for Java.

Because oraxml supports schema validation, include xschema.jar also in

your CLASSPATH

Your PATH environment variable can find the java interpreter that comes with

JDK 1.1.x or JDK 1.2.



Use the following syntax to invoke oraxml:

oraxml options source



oraxml expects to be given an XML file to parse. Table 4–2 lists oraxml’s command

line options.



4-36



Oracle9i XML Developer’s Kits Guide - XDK



Using JAXP



Table 4–2 oraxml: Command Line Options

Option



Purpose



-comp fileName



Compresses the input XML file.



-decomp fileName



Decompresses the input compressed file.



-dtd fileName



Validates the input file with DTD Validation.



-enc fileName



Prints the encoding of the input file



-help



Prints the help message.



-log logfile



Writes the errors/logs to the output file.



-novalidate fileName



Checks whether the input file is well-formed.



-schema fileName



Validates the input file with Schema Validation.



-version



Prints the release version



-warning



Show warnings.



Using JAXP

The Java API for XML Processing (JAXP) gives you the ability to use the SAX,

DOM, and XSLT processors from your Java application. JAXP enables applications

to parse and transform XML documents using an API that is independent of a

particular XML processor implementation.

JAXP has a pluggability layer that enables you to plug in an implementation of a

processor. The JAXP APIs have an API structure consisting of abstract classes

providing a thin layer for parser pluggability. Oracle has implemented JAXP based

on the Sun Microsystems reference implementation.

See Also: More examples can be found at the URL



http://technet.oracle.com/tech/xml

and in the directory xdk/demo/java/parser/jaxp



JAXP Example: (JAVAExamples.java)

import

import

import

import

import



javax.xml.parsers.*;

javax.xml.transform.*;

javax.xml.transform.sax.*;

javax.xml.transform.dom.*;

javax.xml.transform.stream.*;



XML Parser for Java 4-37



Using JAXP



import

import

import

import



java.io.*;

java.util.*;

java.net.URL;

java.net.MalformedURLException;



import

import

import

import



org.xml.sax.*;

org.xml.sax.ext.*;

org.xml.sax.helpers.*;

org.w3c.dom.*;



public class JAXPExamples

{

public static void main(String argv[])

throws TransformerException, TransformerConfigurationException,

IOException, SAXException,

ParserConfigurationException, FileNotFoundException

{

try {

URL xmlURL = createURL("jaxpone.xml");

String xmlID = xmlURL.toString();

URL xslURL = createURL("jaxpone.xsl");

String xslID = xslURL.toString();

//

System.out.println("--- basic ---");

basic(xmlID, xslID);

System.out.println();

System.out.println("--- identity ---");

identity(xmlID);

//

URL generalURL = createURL("general.xml");

String generalID = generalURL.toString();

URL ageURL = createURL("age.xsl");

String ageID = ageURL.toString();

System.out.println();

System.out.println("--- namespaceURI ---");

namespaceURI(generalID, ageID);

//

System.out.println();

System.out.println("--- templatesHandler ---");

templatesHandler(xmlID, xslID);

System.out.println();

System.out.println("--- contentHandler2contentHandler ---");

contentHandler2contentHandler(xmlID, xslID);

System.out.println();



4-38



Oracle9i XML Developer’s Kits Guide - XDK



Using JAXP



System.out.println("--- contentHandler2DOM ---");

contentHandler2DOM(xmlID, xslID);

System.out.println();

System.out.println("--- reader ---");

reader(xmlID, xslID);

System.out.println();

System.out.println("--- xmlFilter ---");

xmlFilter(xmlID, xslID);

//

URL xslURLtwo = createURL("jaxptwo.xsl");

String xslIDtwo = xslURLtwo.toString();

URL xslURLthree = createURL("jaxpthree.xsl");

String xslIDthree = xslURLthree.toString();

System.out.println();

System.out.println("--- xmlFilterChain ---");

xmlFilterChain(xmlID, xslID, xslIDtwo, xslIDthree);

} catch(Exception err) {

err.printStackTrace();

}

}

//

public static void basic(String xmlID, String xslID)

throws TransformerException, TransformerConfigurationException

{

TransformerFactory tfactory = TransformerFactory.newInstance();

Transformer transformer = tfactory.newTransformer(new

StreamSource(xslID));

StreamSource source = new StreamSource(xmlID);

transformer.transform(source, new StreamResult(System.out));

}

//

public static void identity(String xmlID)

throws TransformerException, TransformerConfigurationException

{

TransformerFactory tfactory = TransformerFactory.newInstance();

Transformer transformer = tfactory.newTransformer();

transformer.setOutputProperty(OutputKeys.METHOD, "html");

transformer.setOutputProperty(OutputKeys.INDENT, "no");

StreamSource source = new StreamSource(xmlID);

transformer.transform(source, new StreamResult(System.out));

}

//

public static void namespaceURI(String xmlID, String xslID)

throws TransformerException, TransformerConfigurationException

{



XML Parser for Java 4-39



Xem Thêm
Tải bản đầy đủ (.pdf) (774 trang)

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×