15

我在文件中找到了 dtd,但无法将其删除。当我尝试在 Java 中解析它时,我得到“由:java.net.SocketException:网络无法访问:连接”,因为它的远程 dtd。我可以以某种方式禁用 dtd 检查吗?

4

3 回答 3

19

您应该能够指定自己的 EntityResolver,或者使用解析器的特定功能?有关一些方法,请参见此处

一个更完整的例子:

<?xml version="1.0"?>
<!DOCTYPE foo PUBLIC "//FOO//" "foo.dtd">
<foo>
    <bar>Value</bar>
</foo>

和xpath用法:

import java.io.File;
import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class Main {

    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();

        builder.setEntityResolver(new EntityResolver() {

            @Override
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                System.out.println("Ignoring " + publicId + ", " + systemId);
                return new InputSource(new StringReader(""));
            }
        });
        Document document = builder.parse(new File("src/foo.xml"));
        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        String content = xpath.evaluate("/foo/bar/text()", document
                .getDocumentElement());
        System.out.println(content);
    }
}

希望这可以帮助...

于 2008-10-28T15:29:48.793 回答
15

这对我有用:

 SAXParserFactory saxfac = SAXParserFactory.newInstance();
  saxfac.setValidating(false);
  try {
    saxfac.setFeature("http://xml.org/sax/features/validation", false);
    saxfac.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    saxfac.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    saxfac.setFeature("http://xml.org/sax/features/external-general-entities", false);
    saxfac.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
  }
  catch (Exception e1) {
    e1.printStackTrace();
  }
于 2010-03-01T18:13:03.113 回答
2

我以前遇到过这个问题。我通过下载和存储 DTD 的本地副本然后针对本地副本进行验证来解决它。您需要编辑 XML 文件以指向本地副本。

<!DOCTYPE root-element SYSTEM "filename">

更多信息在这里: http ://www.w3schools.com/dtd/dtd_intro.asp

我认为您也可以在解析器中手动将某种 validateOnParse 属性设置为“false”。取决于您用于解析 XML 的库。

更多信息在这里:http ://www.w3schools.com/dtd/dtd_validation.asp

于 2008-10-28T15:33:40.767 回答