Skip to main content
 首页 » 编程设计

python:检查 XSD xml 模式

2025年05月04日30bonelee

我想检查 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 中搜索了其他模式解析器,但目前没有适合这种情况的东西。

问候,

请您参考如下方法:

PyXB可以处理 xsd:include。我将 PyXB 用于 Amazon.com 的庞大产品架构文件,其中包含的文件包含多个级别的更多 xsd 文件。强烈推荐。