在java程序中用DTD来验证xml格式不起作用是为什么?请教高手

07-02-01 perfectwxj
try {

InputStream in=new FileInputStream(filePath);

SAXReader saxReader = new SAXReader();

this.document = saxReader.read(in);

DocumentBuilderFactory factory = null;

factory = DocumentBuilderFactory.newInstance();

//进行dtd检查

factory.setValidating(true);

} catch (Exception e) {

}

这样写了 但是没有作用

请问该如何设置 saxReader才可以校验

banq
2007-02-01 12:14
校验时必须连上互联网,它缺省是根据http的DTD来校验的。

你需要手工做个转换,将其切换到本地的DTD

perfectwxj
2007-02-01 14:02
不好意思,我还是不太明白怎么用

我把写好的dtd文件放在了根目录下

在xml文件里

<!DOCTYPE issue SYSTEM "http://127.0.0.1:7001/test/test.dtd">

这样引用了外部的dtd

当用dom4j解析xml的时候没有检查我引用的这个文件

能不能给个类似的java的解析例子

谢谢

perfectwxj
2007-02-01 14:03
“你需要手工做个转换,将其切换到本地的DTD ”

能不能给段代码说明如何转换

arrowsky
2007-02-02 16:32
SAXBuilder builder=new SAXBuilder();

builder.setEntityResolver(new YourDTDResolver());

builder.setValidation(true);

YourDTDResolver implements EntityResolver,实现接口定义的

public abstract InputSource resolveEntity (String publicId,String systemId) throws SAXException, IOException;

方法,在其中添加可以从本地加载dtd的方法,如:

public InputSource resolveEntity(String publicId, String systemId) {

if (systemId != null && systemId.startsWith(URL)) {

logger.debug("trying to locate " + systemId + " in classpath under "+CONFIG_PATH);

// Search for DTD

String path = CONFIG_PATH + systemId.substring(URL.length());

InputStream dtdStream = resourceLoader == null ? getClass()

.getResourceAsStream(path) : resourceLoader

.getResourceAsStream(path);

if (dtdStream == null) {

logger.debug(systemId + " not found in classpath");

return null;

} else {

logger.debug("found " + systemId + " in classpath");

InputSource source = new InputSource(dtdStream);

source.setPublicId(publicId);

source.setSystemId(systemId);

return source;

}

} else {

// use the default behaviour

return null;

}

}

我这样讲你明白吗?

perfectwxj
2007-02-02 16:57
呵呵 还是不太明白

先谢谢楼上的

我用的是dom4j解析的xml文件

StringBuffer errorBuff = new StringBuffer();

InputStream in=new FileInputStream(filePath);

SAXReader saxReader = new SAXReader();

PlanlistHandler handler = new PlanlistHandle(filePath,errorBuff);

DocumentBuilderFactory factory=null;

factory=DocumentBuilderFactory.newInstance();

factory.setValidating(true);

factory.setNamespaceAware(true);

saxReader.setProperty("http://xml.org/sax/properties/lexicalhandler", handler);

this.document = saxReader.read(in);

设置了saxReader.setProperty也没有用

现在想知道 怎么样能注册上handler

猜你喜欢