时间:2010-07-25 18:05:26

标签: python python-2.6 xsd-validation amara

2 个答案:

答案 0 :(得分:5)

如果您愿意使用amara以外的其他图书馆,请尝试lxml。它非常容易支持你想要做的事情:

from lxml import etree

source_file = 'test.xml'
schema_file = 'test.xsd'

with open(schema_file) as f_schema:

    schema_doc = etree.parse(f_schema)
    schema = etree.XMLSchema(schema_doc)
    parser = etree.XMLParser(schema = schema)

    with open(source_file) as f_source:
        try:
            doc = etree.parse(f_source, parser)
        except etree.XMLSyntaxError as e:
            # this exception is thrown on schema validation error
            print e

答案 1 :(得分:1)

我建议您使用noNamespaceSchemaLocation属性将XML文件绑定到XSD架构。然后你的XML文件test.xml将是

<?xml version="1.0" encoding="utf-8"?>
<test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="test.xsd">abcde</test>

文件test.xsd

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           elementFormDefault="qualified">
    <xs:element name="test" type="xs:NCName"/>
</xs:schema>

应与test.xsd放在同一目录中。从XML文件引用XML模式是一般技术,它应该在Python中工作。

优点是您不需要知道每个XML文件的模式文件。它将在解析(etree.parse)XML文件时自动找到。