【问题标题】:Error while unmarshal an XML with JAXB caused by DTD file使用 DTD 文件导致的 JAXB 解组 XML 时出错
【发布时间】:2015-09-26 10:04:50
【问题描述】:

我尝试使用 JAXB (javax.xml.bind.JAXB) 解组文件 XML 文件 (test.xml),但它给了我这个错误:

[org.xml.sax.SAXParseException;系统标识: 文件:/C:/Users/EXAMPLE/AppData/Local/Eclipse/workspace_4.4.0/EXAMPLE/test.xml; 行号:2;列号:42;外部 DTD:Lesen von externer DTD "example.dtd" nicht erfolgreich, da "文件"-Zugriff wegen der von der Eigenschaft "accessExternalDTD" festgelegten Einschränkung nicht zulässigist.]

英文翻译:

从外部 DTD "example.dtd" 读取不成功,原因 “文件”- 属性设置的限制不允许访问 "访问外部DTD"

已经尝试过的解决方案:

  • 检查是否所有用户(包括系统)都可以访问 R/W 两个文件。
  • 已删除并使用新文件进行测试。
  • 试图找到这个accessExternalDTD 属性。

注意事项:

  • 项目正在 Subversion 中运行
  • 我在以前的项目中使用了相同的方法和相同的.dtd.xml 文件,效果很好
  • 来自 XML 文件的第 2 行的内容:<!DOCTYPE EXAMPLE SYSTEM "example.dtd">

【问题讨论】:

    标签: java xml jaxb dtd unmarshalling


    【解决方案1】:

    accessExternalDTD 属性可以用系统属性javax.xml.accessExternalDTD 控制,所以用-Djavax.xml.accessExternalDTD=true 启动你的程序,它应该可以工作。也应该可以在解组器上设置属性,试试这个:

    unmarshaller.setProperty(javax.xml.XMLConstants.ACCESS_EXTERNAL_DTD, Boolean.TRUE);
    

    【讨论】:

    • 感谢您的分配!我会尽快尝试,如果它有效,我可以接受你的回答:)
    • "-Djavax.xml.accessExternalDTD=true" 不起作用,"-Djavax.xml.accessExternalDTD=all" 起作用!更可移植的是在代码中执行此操作: System.setProperty("javax.xml.accessExternalDTD", "all"); unmarshaller.setProperty() 解决方案对我不起作用。
    • @HammerNL 你是我的救星!这可能值得拥有自己的主题或作为另一个答案。
    • 这个答案没有解释 accessExternalDTD=all 的作用,或者这样做是否安全。
    【解决方案2】:
    import javax.xml.bind.*;
    import javax.xml.stream.*;
    import javax.xml.transform.stream.StreamSource;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            JAXBContext jc = JAXBContext.newInstance(Customer.class);
    
            XMLInputFactory xif = XMLInputFactory.newFactory();
            xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
            XMLStreamReader xsr = xif.createXMLStreamReader(new StreamSource("input.xml"));
    
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            Customer customer = (Customer) unmarshaller.unmarshal(xsr);
        }
    
    }
    

    【讨论】:

    • 这确实解决了异常,但请注意,此 DISABLES DTD 检查可能不是您想要的!
    猜你喜欢
    • 1970-01-01
    • 2011-04-04
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    相关资源
    最近更新 更多