【发布时间】:2011-02-12 19:35:40
【问题描述】:
我想在 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 中搜索过其他模式解析器,但目前没有适合这种情况的东西。
您好,
【问题讨论】:
-
你能发布预期的结果吗?