使用 DTD 文件导致的 JAXB 解组 XML 时出错

Error while unmarshal an XML with JAXB caused by DTD file

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

[org.xml.sax.SAXParseException; systemId: file:/C:/Users/EXAMPLE/AppData/Local/Eclipse/workspace_4.4.0/EXAMPLE/test.xml; lineNumber: 2; columnNumber: 42; Externe DTD: Lesen von externer DTD "example.dtd" nicht erfolgreich, da "file"-Zugriff wegen der von der Eigenschaft "accessExternalDTD" festgelegten Einschränkung nicht zulässig ist.]

英文翻译:

Reading from external DTD "example.dtd" not succesful , cause "File"-Access is not allowed by the Restriction set by the Properties "accessExternalDTD"

已经尝试过的解决方案:

注意事项:

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

unmarshaller.setProperty(javax.xml.XMLConstants.ACCESS_EXTERNAL_DTD, Boolean.TRUE);
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);
    }

}