我想检查 python 中的 XSD 模式。目前我正在使用 lxml,当它只需要根据架构验证文档时,它的工作非常好。但是,我想知道架构中的内容并访问 lxml 行为中的元素。
架构:
<?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 代码是(简化的):
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)
然后,我可以使用schema_document
(即etree._Element
)将模式作为 XML 文档进行浏览。但是因为etree.fromstring
(至少看起来是这样)需要一个 XML 文档,xsd:include
所以不会处理元素。
目前解决问题的方法是解析第一个schema文档,然后加载include元素,然后手动将它们一个一个插入到主文档中:
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)
我要求的是如何通过使用更常见的方式来解决问题的想法。我已经在 python 中搜索了其他模式解析器,但现在没有任何东西适合这种情况。
问候,