用SAX怎么样检查XML的正确性?

GFox 2002-03-24 10:40:28
DOM的我知道,SAX呢?怎么做呢?
最好有个例子
...全文
63 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
GFox 2002-03-28
  • 打赏
  • 举报
回复
好的,我晚上试试,现在不方便下 ^_^

不管怎么说,谢谢你还有其它大侠了,我先给分了吧 ^_^
superszhu 2002-03-28
  • 打赏
  • 举报
回复
兄弟,去下一个JAXP吧,
http://java.sun.com/xml/downloads/javaxmlpack.html
文件在examples\SAXTagCount下
GFox 2002-03-27
  • 打赏
  • 举报
回复
老兄,它说

"SAXTagCount.java": Error #: 300 : method getXMLReader() not found in class javax.xml.parsers.SAXParser at line 121, column 35

??
superszhu 2002-03-26
  • 打赏
  • 举报
回复
JAXP 自带的例子:


import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;

import java.util.*;
import java.io.*;

/**
* Program to count the number of "tags" AKA elements in an XML document.
* This example also shows one way to turn on validation and how to use a
* SAX ErrorHandler.
*
* Notes: DefaultHandler is a SAX helper class that implements the SAX
* ContentHandler interface by providing no-op methods. This class
* overrides some of the methods by extending DefaultHandler.
*
*/
public class SAXTagCount extends DefaultHandler {
// A Hashtable with tag names as keys and Integers as values
private Hashtable tags;

// Parser calls this once at the beginning of a document
public void startDocument() throws SAXException {
tags = new Hashtable();
}

// Parser calls this for each element in a document
public void startElement(String namespaceURI, String localName,
String rawName, Attributes atts)
throws SAXException
{
String key = localName;
Object value = tags.get(key);
if (value == null) {
// Add a new entry
tags.put(key, new Integer(1));
} else {
// Get the current count and increment it
int count = ((Integer)value).intValue();
count++;
tags.put(key, new Integer(count));
}
}

// Parser calls this once after parsing a document
public void endDocument() throws SAXException {
Enumeration e = tags.keys();
while (e.hasMoreElements()) {
String tag = (String)e.nextElement();
int count = ((Integer)tags.get(tag)).intValue();
System.out.println("Tag <" + tag + "> occurs " + count
+ " times");
}
}

/**
* Convert from a filename to a file URL.
*/
private static String convertToFileURL(String filename) {
// On JDK 1.2 and later, simplify this to:
// "path = file.toURL().toString()".
String path = new File(filename).getAbsolutePath();
if (File.separatorChar != '/') {
path = path.replace(File.separatorChar, '/');
}
if (!path.startsWith("/")) {
path = "/" + path;
}
return "file:" + path;
}

private static void usage() {
System.err.println("Usage: SAXTagCount [-v] <filename>");
System.err.println(" -v = validation");
System.exit(1);
}

static public void main(String[] args) {
String filename = null;
boolean validation = false;

// Parse arguments
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-v")) {
validation = true;
} else {
filename = args[i];

// Must be last arg
if (i != args.length - 1) {
usage();
}
}
}
if (filename == null) {
usage();
}

// There are several ways to parse a document using SAX and JAXP.
// We show one approach here. The first step is to bootstrap a
// parser. There are two ways: one is to use only the SAX API, the
// other is to use the JAXP utility classes in the
// javax.xml.parsers package. We use the second approach here
// because it allows the application to use a platform default
// implementation without having to specify a system property.
// After bootstrapping a parser/XMLReader, there are several ways
// to begin a parse. In this example, we use the SAX API.

// Create a JAXP SAXParserFactory and configure it
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setValidating(validation);

XMLReader xmlReader = null;
try {
// Create a JAXP SAXParser
SAXParser saxParser = spf.newSAXParser();

// Get the encapsulated SAX XMLReader
xmlReader = saxParser.getXMLReader();
} catch (Exception ex) {
System.err.println(ex);
System.exit(1);
}

// Set the ContentHandler of the XMLReader
xmlReader.setContentHandler(new SAXTagCount());

// Set an ErrorHandler before parsing
xmlReader.setErrorHandler(new MyErrorHandler(System.err));

try {
// Tell the XMLReader to parse the XML document
xmlReader.parse(convertToFileURL(filename));
} catch (SAXException se) {
System.err.println(se.getMessage());
System.exit(1);
} catch (IOException ioe) {
System.err.println(ioe);
System.exit(1);
}
}

// Error handler to report errors and warnings
private static class MyErrorHandler implements ErrorHandler {
/** Error handler output goes here */
private PrintStream out;

MyErrorHandler(PrintStream out) {
this.out = out;
}

/**
* Returns a string describing parse exception details
*/
private String getParseExceptionInfo(SAXParseException spe) {
String systemId = spe.getSystemId();
if (systemId == null) {
systemId = "null";
}
String info = "URI=" + systemId +
" Line=" + spe.getLineNumber() +
": " + spe.getMessage();
return info;
}

// The following methods are standard SAX ErrorHandler methods.
// See SAX documentation for more info.

public void warning(SAXParseException spe) throws SAXException {
out.println("Warning: " + getParseExceptionInfo(spe));
}

public void error(SAXParseException spe) throws SAXException {
String message = "Error: " + getParseExceptionInfo(spe);
throw new SAXException(message);
}

public void fatalError(SAXParseException spe) throws SAXException {
String message = "Fatal Error: " + getParseExceptionInfo(spe);
throw new SAXException(message);
}
}
}
GFox 2002-03-25
  • 打赏
  • 举报
回复
to: superszhu(精彩世界)

可不可以详细点?我刚刚学XML,谢谢^_^
GFox 2002-03-25
  • 打赏
  • 举报
回复
要是XML不符合它的DTD,会怎么样?

to: flytsu(卡休)

我有这样用,不过当XML不符合DTD时,好像也没有调用ErrorHandler的什么方法?
superszhu 2002-03-25
  • 打赏
  • 举报
回复
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setValidating(true);
flytsu 2002-03-25
  • 打赏
  • 举报
回复
参考一下几个类的用法。
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXParseException;

例程:
class MyErrorHandler implements ErrorHandler{//inner class that implements Interface ErrorHandler
public void warning(SAXParseException exception) throws SAXException{
System.out.println("**Parsing Warning**\n"+
" Line: "+
exception.getLineNumber()+"\n"+
"URI: "+
exception.getSystemId()+"\n"+
"Message: "+
exception.getMessage());
throw new SAXException("Warning encountered");

}
public void error(SAXParseException exception)throws SAXException{
System.out.println("**Parsing Error**\n"+
" Line: "+
exception.getLineNumber()+"\n"+
"URI: "+
exception.getSystemId()+"\n"+
"Message: "+
exception.getMessage());
throw new SAXException("Error encountered");
}
public void fatalError(SAXParseException exception) throws SAXException{
System.out.println("*****Parsing Error*****\n"+
" Line: "+
exception.getLineNumber()+"\n"+
"URI: "+
exception.getSystemId()+"\n"+
"Message: "+
exception.getMessage());
throw new SAXException("Fatal Error encountered");
}
}

tinyxpath 解析简单 的小工具,输出是一个静态库。可 找到xml文档. TinyXml介绍 TinyXml是一个基于DOM模型的、非验证的轻量级C++解释器 一. XML解析模型: 目前XML的解析主要有两大模型:SAX和DOM。 SAX是基于事件的,其基本工作流程是分析XML文档,当发现了一个新的元素时,产生一个对应事件,并调用相应的用户处理函数。这种方式占用内存少,速度快,但用户程序相应得会比较复杂。 DOM(文档对象模型),则是在分析时,一次性的将整个XML文档进行分析,并在内存中形成对应的树结构,同时,向用户提供一系列的接口来访问和编辑该树结构。这种方式占用内存大,速度往往慢于SAX,但可以给用户提供一个面向对象的访问接口,对用户更为友好。 另据说,一些同时提供了SAX和DOM接口的库,是在底层先实现SAX,再在SAX的基础上实现DOM 对于一个特定的XML文档而言,其正确性分为两个层次。 首先是其格式应该符合XML的基本格式要求,比如第一行要有声明,标签的嵌套层次必须前后一致等等,符合这些要求的文件,就是一个合格的XML文件,称作well-formatted。 其次,一个XML文档因其内容的不同还必须在语义上符合相应的标准,这些标准由相应的DTD文件或者Schema文件来定义,符合了这些定义要求的XML文件,称作valid。 因此,解析器也分为两种,一种是验证的,即会跟据XML文件中的声明,用相应的DTD文件对XML文件进行校验,检查它是否满足DTD文件的要求。另一种是忽略DTD文件,只要基本格式正确,就可以进行解析。 就我所知,验证的解析器通常都是比较重量级的。TinyXml不支持验证,但是体积很小,用在解析格式较为简单的XML文件,比如配置文件时,特别的合适。

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧