当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《如何在java的xpath中在运行时禁用dtd?》经验,为你挑选了2个好方法。

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



1> toolkit..:

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

一个更完整的例子:




    Value

和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> David..:

这对我有用:

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


+1 - 这是最好的答案 - 但是只使用这一行就足够了:``saxfac.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",false) ;``
推荐阅读
郑小蒜9299_941611_G
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有