lxml XMLSchema オブジェクトを使用して、xs:ID および xs:IDREF 制約を指定する xsd に対して xml ファイルを検証しています。ただし、IDREF に対応する ID がない場合でも、lxml は明らかに xml ドキュメントを true に検証します。
この問題を解決する方法についてのアイデアはありますか?
編集:
XSD:
<xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.chaos.com"
xmlns="http://www.chaos.com"
elementFormDefault="qualified">
<xs:complexType name="ModuleType">
<xs:attribute name="id" type="xs:ID" use="required"/>
<xs:attribute name="path" type="xs:string" use="required"/>
<xs:anyAttribute processContents="lax"/>
</xs:complexType>
<xs:complexType name="ModulesType" mixed="true">
<xs:sequence>
<xs:element name="Module" type="ModuleType" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
<xs:anyAttribute processContents="lax"/>
</xs:complexType>
<xs:complexType name="FrameworkType" mixed="true">
<xs:all>
<xs:element name="Good">
<xs:complexType>
<xs:attribute name="moduleId" type="xs:IDREF" use="required"/>
<xs:anyAttribute processContents="lax"/>
</xs:complexType>
</xs:element>
<xs:element name="Bad">
<xs:complexType>
<xs:attribute name="moduleId" type="xs:IDREF" use="required"/>
<xs:anyAttribute processContents="lax"/>
</xs:complexType>
</xs:element>
</xs:all>
<xs:anyAttribute processContents="lax"/>
</xs:complexType>
<xs:complexType name="TestbenchType" mixed="true">
<xs:sequence>
<xs:element name="Modules" type="ModulesType"/>
<xs:element name="Framework" type="FrameworkType"/>
</xs:sequence>
</xs:complexType>
<xs:element name="Testbench" type="TestbenchType"/>
</xs:schema>
XML:
<Testbench xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.chaos.com">
<Modules>
<Module id="Module1" path="Testbench_module1.py"/>
<Module id="Module2" path="Testbench_module2.py"/>
</Modules>
<Framework>
<Good moduleId="Module1"/>
<Bad moduleId="ModuleX"/>
</Framework>
</Testbench>
Python 検証コード:
from lxml import etree
from cStringIO import StringIO
try:
#Get schema
buf_schema = StringIO()
with open(schema,'r') as fh:
for line in fh: buf_schema.write(line)
buf_schema.seek(0)
Schema = etree.XMLSchema(etree.parse(buf_schema))
buf_schema.close()
# Validate
buf_cfg = StringIO()
with open(cfg,'r') as fh:
for line in fh: buf_cfg.write(line)
buf_cfg.seek(0)
Schema.assertValid(etree.parse(buf_cfg))
buf_cfg.close()
except etree.XMLSyntaxError, err:
return False, str(err)
except Exception, err:
return False, str(err)
return True,None
この関数は、要素 Bad の属性 moduleId が IDREF 制約に違反している場合でも、指定された XSD/XML に対して True を返します。