Luis Masuelli
Luis Masuelli

Reputation: 12333

How can I fix an XSD import error in lxml?

I run this validation using 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)

Assume xml_content and xsd_content are correctly instantiated. Part of the xsd content is this:

<?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>

When I run the script I get an error:

failed to load external entity "xmldsig-core-schema.xsd"

When I hit http://www.w3.org/2000/09/xmldsig# in a browser, I get a xsd content.

Q: What am I missing here? How can I avoid such error?

Edit Notes:

  1. This error occurs before the validation can be made (i.e. this error occurs in the XMLSchema constructor).
  2. The xsd file is provided from an external source and I'm not allowed to edit it.

Upvotes: 7

Views: 5098

Answers (1)

kjhughes
kjhughes

Reputation: 111521

Make sure that you have a copy of xmldsig-core-schema.xsd in the same directory as the importing XSD.

If you wish to located the imported XSD elsewhere in your filesystem, you can use absolute paths in URI notation. For example, on Windows:

<xsd:import namespace="http://www.w3.org/2000/09/xmldsig#"
            schemaLocation="file:///c:/path/to/your/xsd/xmldsig-core-schema.xsd" />

Or change this:

<xsd:import namespace="http://www.w3.org/2000/09/xmldsig#"
            schemaLocation="xmldsig-core-schema.xsd" />

to this:

<xsd:import namespace="http://www.w3.org/2000/09/xmldsig#"
            schemaLocation="http://www.w3.org/2000/09/xmldsig" />

to access the remote copy, which you've verified is at that endpoint.

Upvotes: 3

Related Questions