python:检查XSD-xml模式

2024-10-01 15:38:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我想研究一下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代码是(简化的):

^{pr2}$

然后我就可以使用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中搜索过其他模式解析器,但目前还没有适合这种情况的。在

您好


Tags: 文档url元素baseincludeschema模式document

热门问题