如何在java的xpath中禁用运行时的dtd?

2022-09-03 04:27:17

我在文件中得到了dtd,我无法删除它。当我尝试在Java中解析它时,我得到“由:java.net.SocketException:Network is unreable:connect”引起,因为它的远程dtd。我可以以某种方式禁用dtd检查吗?


答案 1

您应该能够指定自己的实体解析器,或者使用解析器的特定功能?有关某些方法,请参阅此处。

一个更完整的示例:

<?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);
    }
}

希望这有帮助...


答案 2

这对我有用:

 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();
  }

推荐