gpt4 book ai didi

Java、XML、XSLT : Prevent DTD-Validation

转载 作者:数据小太阳 更新时间:2023-10-29 01:54:45 24 4
gpt4 key购买 nike

我使用 Java (6) XML-Api 对来自网络的 html 文档应用 xslt 转换。该文档是格式良好的 xhtml,因此包含有效的 DTD-Spec (<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">)。现在出现了一个问题:XSLT 处理器尝试下载 DTD,而 w3 服务器通过 HTTP 503 错误(由于 w3 的 Bandwith Limitation)拒绝了这一点。

如何防止 XSLT 处理器下载 dtd?我不需要验证我的输入文档。

来源是:

import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

--

   String xslt = "<?xml version=\"1.0\"?>"+
"<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">"+
" <xsl:output method=\"text\" />"+
" <xsl:template match=\"//html/body//div[@id='bodyContent']/p[1]\"> "+
" <xsl:value-of select=\".\" />"+
" </xsl:template>"+
" <xsl:template match=\"text()\" />"+
"</xsl:stylesheet>";

try {
Source xmlSource = new StreamSource("http://de.wikipedia.org/wiki/Right_Livelihood_Award");
Source xsltSource = new StreamSource(new StringReader(xslt));
TransformerFactory ft = TransformerFactory.newInstance();

Transformer trans = ft.newTransformer(xsltSource);

trans.transform(xmlSource, new StreamResult(System.out));
}
catch (Exception e) {
e.printStackTrace();
}

我在 SO 上阅读了以下问题,但它们都使用另一个 XML-Api:

谢谢!

最佳答案

我最近在使用 JAXB 解码 XML 时遇到了这个问题。答案是从 XmlReader 和 InputSource 创建 SAXSource,然后将其传递给 JAXB UnMarshaller 的 unmarshal() 方法。为了避免加载外部 DTD,我在 XmlReader 上设置了自定义 EntityResolver。

SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xmlr = sp.getXMLReader();
xmlr.setEntityResolver(new EntityResolver() {
public InputSource resolveEntity(String pid, String sid) throws SAXException {
if (sid.equals("your remote dtd url here"))
return new InputSource(new StringReader("actual contents of remote dtd"));
throw new SAXException("unable to resolve remote entity, sid = " + sid);
} } );
SAXSource ss = new SAXSource(xmlr, myInputSource);

如前所述,如果有人要求此自定义实体解析器解析您希望它解析的实体以外的实体,它就会抛出异常。如果您只是想让它继续加载远程实体,请删除“throws”行。

关于Java、XML、XSLT : Prevent DTD-Validation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1572808/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com