如何修复lxml中的XSD导入错误?

Lui*_*lli 6 python xsd lxml

我使用lxml运行此验证:

parser = etree.XMLParser()

try:
    root = etree.fromstring(xml_content.strip(), parser)
except Exception as e:
    raise XMLFormatException(str(e), XMLFormatException.IN_XML)

try:
    schema = etree.XMLSchema(etree.XML(xsd_content.strip()))
except Exception as e:
    raise XMLFormatException(str(e), XMLFormatException.IN_XSD)

if not schema.validate():
    raise XMLValidationException("Se produjo un error al validar el XML", schema.error_log)
Run Code Online (Sandbox Code Playgroud)

假设xml_contentxsd_content正确实例化.部分xsd内容是这样的:

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            xmlns:ds="http://www.w3.org/2000/09/xmldsig#" elementFormDefault="qualified">
    <xsd:import namespace="http://www.w3.org/2000/09/xmldsig#"
                schemaLocation="xmldsig-core-schema.xsd" />
    <!-- more stuff here -->
</xsd:schema>
Run Code Online (Sandbox Code Playgroud)

当我运行脚本时,我收到一个错误:

无法加载外部实体"xmldsig-core-schema.xsd"

当我在浏览器中访问http://www.w3.org/2000/09/xmldsig#时,我得到了一个xsd内容.

:我在这里错过了什么?我怎样才能避免这样的错误?

编辑笔记:

  1. 在进行验证之前发生此错误(即在XMLSchema构造函数中发生此错误).
  2. xsd文件是从外部源提供的,我不允许编辑它.

kjh*_*hes 3

确保您在导入 XSD 的同一目录中拥有 xmldsig-core-schema.xsd 的副本。

如果您希望将导入的 XSD 定位在文件系统中的其他位置,则可以在 URI 表示法中使用绝对路径。例如,在 Windows 上:

<xsd:import namespace="http://www.w3.org/2000/09/xmldsig#"
            schemaLocation="file:///c:/path/to/your/xsd/xmldsig-core-schema.xsd" />
Run Code Online (Sandbox Code Playgroud)

或者改变这个:

<xsd:import namespace="http://www.w3.org/2000/09/xmldsig#"
            schemaLocation="xmldsig-core-schema.xsd" />
Run Code Online (Sandbox Code Playgroud)

对此:

<xsd:import namespace="http://www.w3.org/2000/09/xmldsig#"
            schemaLocation="http://www.w3.org/2000/09/xmldsig" />
Run Code Online (Sandbox Code Playgroud)

访问您已验证位于该端点的远程副本。