我在文件中得到了dtd而我无法将其删除。当我尝试用Java解析它时,我得到“引起:java.net.SocketException:网络无法访问:连接”,因为它的远程dtd。我能以某种方式禁用dtd检查吗?
答案 0 :(得分:18)
您应该能够指定自己的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);
}
}
希望这会有所帮助......
答案 1 :(得分:14)
这对我有用:
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();
}
答案 2 :(得分:2)
之前我遇到过这个问题。我通过下载并存储DTD的本地副本然后验证本地副本来解决它。您需要编辑XML文件以指向本地副本。
<!DOCTYPE root-element SYSTEM "filename">
此处有更多信息:http://www.w3schools.com/dtd/dtd_intro.asp
我认为您还可以在解析器中手动将某种validateOnParse属性设置为“false”。取决于您用于解析XML的库。