gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:01:45 24 4
gpt4 key购买 nike

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

最佳答案

您应该能够指定您自己的 EntityResolver,或者使用您的解析器的特定功能?参见 here对于某些方法。

一个更完整的例子:

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

希望这有助于...

关于java - 如何在运行时在 java 的 xpath 中禁用 dtd?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/243728/

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