Python: check XSD xml schema
I would like to review an XSD schema in python. I am currently using lxml, which does the job very well when it only needs to validate a document against a schema. But I want to know what's inside the schema and access the elements in the lxml behavior.
Scheme:
<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:include schemaLocation="worker_remote_base.xsd"/>
<xsd:include schemaLocation="transactions_worker_responses.xsd"/>
<xsd:include schemaLocation="transactions_worker_requests.xsd"/>
</xsd:schema>
Lxml code to load schema (simple):
xsd_file_handle = open( self._xsd_file, 'rb')
xsd_text = xsd_file_handle.read()
schema_document = etree.fromstring(xsd_text, base_url=xmlpath)
xmlschema = etree.XMLSchema(schema_document)
Then I can use schema_document
(which is etree._Element
) to traverse the schema as an XML document. But since etree.fromstring
(at least it looks like) expecting an XML document, no elements xsd:include
are processed.
The issue is currently resolved by parsing the first schematic document, then loading the included items, and then manually inserting them one by one into the main document:
BASE_URL = "/xml/"
schema_document = etree.fromstring(xsd_text, base_url=BASE_URL)
tree = schema_document.getroottree()
schemas = []
for schemaChild in schema_document.iterchildren():
if schemaChild.tag.endswith("include"):
try:
h = open (os.path.join(BASE_URL, schemaChild.get("schemaLocation")), "r")
s = etree.fromstring(h.read(), base_url=BASE_URL)
schemas.append(s)
except Exception as ex:
print "failed to load schema: %s" % ex
finally:
h.close()
# remove the <xsd:include ...> element
self._schema_document.remove(schemaChild)
for s in schemas:
# inside <schema>
for sChild in s:
schema_document.append(sChild)
What I am asking for is an idea of how to solve the problem using a more general way. I've already looked for other schema parsers in python, but now there was nothing in this case.
Hello,
a source to share