如何离线使用dom4j SAXReader?

Ode*_*gev 4 java xml dom4j

我想离线使用SAXReader ,问题是SAXReader正在验证xml是否符合DTD.我不想更改XML中的DTD或其他任何内容.通过在本网站和其他来源搜索,我发现2个答案对我没有帮助:

  1. 使用EntityResolver绕过网络调用
  2. 使用setIncludeExternalDTDDeclarations(false)

我试图做的例子:

protected Document getPlistDocument() throws MalformedURLException,
DocumentException {
    SAXReader saxReader = new SAXReader();
    saxReader.setIgnoreComments(false);
    saxReader.setIncludeExternalDTDDeclarations(false);
    saxReader.setIncludeInternalDTDDeclarations(true);
    saxReader.setEntityResolver(new MyResolver());
    Document plistDocument = saxReader.read(getDestinationFile().toURI().toURL());
    return plistDocument;
}

public class MyResolver implements EntityResolver {
    public InputSource resolveEntity (String publicId, String systemId)
    {
        if (systemId.equals("http://www.myhost.com/today")) {
            // if we want a custom implementation, return a special input source
            return null;

        } else {
            // use the default behaviour
            return null;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
Run Code Online (Sandbox Code Playgroud)

我仍然无法离线工作,请建议......谢谢

堆栈跟踪:

14:20:44,358 ERROR [ApplicationBuilder] iphone build failed: Resource Manager - Problem handle Root.plist: www.apple.com Nested exception: www.apple.com
com.something.builder.sourcemanager.exception.SourceHandlingException: Resource Manager - Problem handle Root.plist: www.apple.com Nested exception: www.apple.com
****
****
Caused by: org.dom4j.DocumentException: www.apple.com Nested exception: www.apple.com
at org.dom4j.io.SAXReader.read(SAXReader.java:484)
at org.dom4j.io.SAXReader.read(SAXReader.java:291)  
... 10 more
Run Code Online (Sandbox Code Playgroud)

JB *_*zet 5

您的实体解析器不处理任何内容(因为它始终返回null).当系统ID为http://www.apple.com/DTDs/PropertyList-1.0.dtd,它使InputSource返回到实际的DTD文件,因为这是dom4j尝试下载的DTD.

public class MyResolver implements EntityResolver {
    public InputSource resolveEntity (String publicId, String systemId)
    {
        if (systemId.equals("http://www.apple.com/DTDs/PropertyList-1.0.dtd")) {
            return new InputSource(MyResolver.class.getResourceAsStream("/dtds/PropertyList-1.0.dtd");
        } else {
            // use the default behaviour
            return null;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

例如,此实现从类路径(在包中dtds)返回DTD .您只需自己下载DTD并将其捆绑在应用程序的包中dtds.