你的位置:3P代码 >> JSP技术 >> Java基础 >> 详细内容 在线投稿

Java XML教程(二)

热度0票  浏览87次 时间:2010年12月29日 11:58

  case Node.ELEMENT_NODE:

elementNodes++;

NodeList children = node.getChildNodes();

if (children != null)

{

int len = children.getLength();

for (int i = 0; i< len; i++)

scanDOMTree(children.item(i));

}

break;

case Node.ENTITY_REFERENCE_NODE:

entityReferenceNodes++;

break;

case Node.CDATA_SECTION_NODE:

cdataSections++;

break;

case Node.TEXT_NODE:

textNodes++;

break;

case Node.PROCESSING_INSTRUCTION_NODE:

processingInstructions++;

break;

}

}

/** Main program entry point. */

public static void main(String argv[])

{

if (argv.length == 0)

{

System.out.println("Usage: java domCounter uri");

System.out.println(" where uri is the URI of your XML document.");

System.out.println(" Sample: java domCounter sonnet.xml");

System.exit(1);

}

domCounter dc = new domCounter();

dc.parseAndCount(argv[0]);

}

}

saxOne.java

/*

* (C) Copyright IBM Corp. 1999 All rights reserved.

*

* US Government Users Restricted Rights Use, duplication or

* disclosure restricted by GSA ADP Schedule Contract with IBM Corp.

*

* The program is provided "as is" without any warranty express or

* implied, including the warranty of non-infringement and the implied

* warranties of merchantibility and fitness for a particular purpose.

* IBM will not be liable for any damages suffered by you as a result

* of using the Program. In no event will IBM be liable for any

* special, indirect or consequential damages or lost profits even if

* IBM has been advised of the possibility of their occurrence. IBM

* will not be liable for any third party claims against you.

*/

import java.io.OutputStreamWriter;

import java.io.PrintWriter;

import java.io.UnsupportedEncodingException;

import org.xml.sax.AttributeList;

import org.xml.sax.HandlerBase;

import org.xml.sax.Parser;

import org.xml.sax.SAXException;

import org.xml.sax.SAXParseException;

import org.xml.sax.helpers.ParserFactory;

import com.ibm.xml.parsers.SAXParser;

/**

* saxOne.java

* This sample program illustrates how to use a SAX parser. It

* parses a document and writes the document? contents back to

* standard output.

*/

public class saxOne

extends HandlerBase

{

public void parseURI(String uri)

{

SAXParser parser = new SAXParser();

parser.setDocumentHandler(this);

parser.setErrorHandler(this);

try

{

parser.parse(uri);

}

catch (Exception e)

{

System.err.println(e);

}

}

/** Processing instruction. */

public void processingInstruction(String target, String data)

{

System.out.print(" 0)

{

System.out.print(` `);

System.out.print(data);

}

System.out.print("?>");

}

/** Start document. */

public void startDocument()

{

System.out.println("");

}

/** Start element. */

public void startElement(String name, AttributeList attrs)

{

System.out.print("<");

System.out.print(name);

if (attrs != null)

{

int len = attrs.getLength();

for (int i = 0; i ");

}

/** Characters. */

public void characters(char ch[], int start, int length)

{

System.out.print(new String(ch, start, length));

}

/** Ignorable whitespace. */

public void ignorableWhitespace(char ch[], int start, int length)

{

characters(ch, start, length);

}

/** End element. */

public void endElement(String name)

{

System.out.print("");

}

/** End document. */

public void endDocument()

{

// No need to do anything.

}

//

// ErrorHandler methods

//

/** Warning. */

public void warning(SAXParseException ex)

{

System.err.println("[Warning] "+

getLocationString(ex)+": "+

ex.getMessage());

}

/** Error. */

public void error(SAXParseException ex)

{

System.err.println("[Error] "+

getLocationString(ex)+": "+

ex.getMessage());

}

/** Fatal error. */

public void fatalError(SAXParseException ex)

throws SAXException

{

System.err.println("[Fatal Error] "+

getLocationString(ex)+": "+

ex.getMessage());

throw ex;

}

/** Returns a string of the location. */

private String getLocationString(SAXParseException ex)

{

StringBuffer str = new StringBuffer();

String systemId = ex.getSystemId();

if (systemId != null)

{

int index = systemId.lastIndexOf(`/`);

if (index != -1)

systemId = systemId.substring(index + 1);

str.append(systemId);

}

str.append(`:`);

str.append(ex.getLineNumber());

str.append(`:`);

str.append(ex.getColumnNumber());

return str.toString();

}

/** Main program entry point. */

public static void main(String argv[])

{

if (argv.length == 0)

{

System.out.println("Usage: java saxOne uri");

System.out.println(" where uri is the URI of your XML document.");

System.out.println(" Sample: java saxOne sonnet.xml");

System.exit(1);

}

saxOne s1 = new saxOne();

s1.parseURI(argv[0]);

}

}

saxCounter.java

/*

* (C) Copyright IBM Corp. 1999 All rights reserved.

*

* US Government Users Restricted Rights Use, duplication or

* disclosure restricted by GSA ADP Schedule Contract with IBM Corp.

*

* The program is provided "as is" without any warranty express or

* implied, including the warranty of non-infringement and the implied

* warranties of merchantibility and fitness for a particular purpose.

* IBM will not be liable for any damages suffered by you as a result

* of using the Program. In no event will IBM be liable for any

* special, indirect or consequential damages or lost profits even if

* IBM has been advised of the possibility of their occurrence. IBM

* will not be liable for any third party claims against you.

*/

import java.io.OutputStreamWriter;

import java.io.PrintWriter;

import java.io.UnsupportedEncodingException;

import org.xml.sax.AttributeList;

import org.xml.sax.HandlerBase;

import org.xml.sax.Parser;

import org.xml.sax.SAXException;

import org.xml.sax.SAXParseException;

import org.xml.sax.helpers.ParserFactory;

import com.ibm.xml.parsers.SAXParser;

/**

* saxCounter.java

* This sample program calculates statistics for an XML document,

* based on the SAX events received. When the parse is complete,

* it prints the statistics to standard output.

*/

public class saxCounter

extends HandlerBase

{

int startDocumentEvents = 0;

int endDocumentEvents = 0;

int startElementEvents = 0;

int endElementEvents = 0;

int processingInstructionEvents = 0;

int characterEvents = 0;

int ignorableWhitespaceEvents = 0;

int warningEvents = 0;

int errorEvents = 0;

int fatalErrorEvents = 0;

public void parseURI(String uri)

{

SAXParser parser = new SAXParser();

parser.setDocumentHandler(this);

parser.setErrorHandler(this);

try

{

parser.parse(uri);

}

catch (Exception e)

{

System.err.println(e);

}

System.out.println("Document Statistics for " + uri + ":");

System.out.println("====================================");

System.out.println("DocumentHandler Events:");

System.out.println(" startDocument " +

startDocumentEvents);

System.out.println(" endDocument " +

endDocumentEvents);

System.out.println(" startElement " +

startElementEvents);

System.out.println(" endElement " +

endElementEvents);

System.out.println(" processingInstruction " +

processingInstructionEvents);

System.out.println(" character " +

characterEvents);

System.out.println(" ignorableWhitespace " +

ignorableWhitespaceEvents);

System.out.println("ErrorHandler Events:");

System.out.println(" warning " +

warningEvents);

System.out.println(" error " +

errorEvents);

System.out.println(" fatalError " +

fatalErrorEvents);

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

int totalEvents = startDocumentEvents + endDocumentEvents +

startElementEvents + endElementEvents +

processingInstructionEvents +

characterEvents + ignorableWhitespaceEvents +

warningEvents + errorEvents + fatalErrorEvents;

System.out.println("Total: " +

totalEvents + " Events");

}

/** Processing instruction. */

public void processingInstruction(String target, String data)

{

processingInstructionEvents++;

}

/** Start document. */

public void startDocument()

{

startDocumentEvents++;

}

/** Start element. */

public void startElement(String name, AttributeList attrs)

{

startElementEvents++;

}

/** Characters. */

public void characters(char ch[], int start, int length)

{

characterEvents++;

}

/** Ignorable whitespace. */

public void ignorableWhitespace(char ch[], int start, int length)

{

ignorableWhitespaceEvents++;

}

/** End element. */

public void endElement(String name)

{

endElementEvents++;

}

/** End document. */

public void endDocument()

{

endDocumentEvents++;

}

//

// ErrorHandler methods

//

/** Warning. */

public void warning(SAXParseException ex)

{

warningEvents++;

}

/** Error. */

public void error(SAXParseException ex)

{

errorEvents++;

}

/** Fatal error. */

public void fatalError(SAXParseException ex)

throws SAXException

{

fatalErrorEvents++;

throw ex;

}

/** Main program entry point. */

public static void main(String argv[])

{

if (argv.length == 0)

{

System.out.println("Usage: java saxCounter uri");

System.out.println(" where uri is the URI of your XML document.");

System.out.println(" Sample: java saxCounter sonnet.xml");

System.exit(1);

}

saxCounter sc = new saxCounter();

sc.parseURI(argv[0]);

} }

TAG: Java JAVA java XML xml XMl Xml 教程
上一篇 下一篇