1

我使用 Saxon(Java) 转换*.xhtml*.xml.

这是我的java代码:

System.setProperty("javax.xml.transform.TransformerFactory","net.sf.saxon.TransformerFactoryImpl");
TransformerFactory tfactory = TransformerFactory.newInstance();
System.out.println("load xslt file");
Templates templates = tfactory.newTemplates(new StreamSource(xsltFile));

Transformer transformer = templates.newTransformer();
Result result = new StreamResult(new File(filtTempXml));
transformer.transform(new StreamSource(xmlFile), result);

因为文件中有DTD *.xhtml,比如:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

错误:

 java.net.SocketException: Unexpected end of file from server

我想知道:

1) 如何简单地禁用 dtd?

2)如果没有,如何在Java程序中为saxon设置目录文件(将dtd映射到本地)?有什么例子吗?

谢谢。

4

1 回答 1

1

最后,我知道如何实现它。

SAXParserFactory parserFactory = SAXParserFactory.newInstance();
SAXParser saxParser = parserFactory.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();

EntityResolver entityReolver = new EntityResolver() {
    public InputSource resolveEntity(String publicId, String systemId) {
    try {
        System.out.println("Entity resolving systemID... " + publicId);
        if (systemId.indexOf((".dtd")) != -1) {
            System.out.println("Entity Resolved...");
            return new InputSource(new ByteArrayInputStream("<?xml version='1.0' encoding='UTF-8'?>".getBytes()));
        }
    } catch (Exception e) {
    }
    return null;
    }
};
xmlReader.setEntityResolver(entityReolver);

SAXSource saxSource = new SAXSource(xmlReader, SAXSource.sourceToInputSource(new   StreamSource(xmlFile)));
transformer.transform(saxSource, result);
于 2011-10-18T01:17:43.987 回答