5

以下 Q 的高额赏金:

您好,这是我在 Ubuntu 9.10 上使用 Python 2.6、Amara2 尝试的(顺便说一下,test.xsd 是使用 xml2xsd 工具创建的):

g@spot:~$ cat test.xml; echo =====o=====; cat test.xsd; echo ==== 
o=====; cat test.py; echo =====o=====; ./test.py; echo =====o===== 
<?xml version="1.0" encoding="utf-8"?>==; ./test.py` > 
test.txttest.xsd; echo === 
<test>abcde</test> 
=====o===== 
<?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> 
=====o===== 
#!/usr/bin/python2.6 
# I wish to validate an xml file against an external XSD schema. 
from amara import bindery, parse 
source = 'test.xml' 
schema = 'test.xsd' 
#help(bindery.parse) 
#doc = bindery.parse(source, uri=schema, validate=True) # These 2 seem 
to fail in the same way. 
doc = parse(source, uri=schema, validate=True) # So, what is the 
difference anyway? 
# 
=====o===== 
Traceback (most recent call last): 
  File "./test.py", line 14, in <module> 
    doc = parse(source, uri=schema, validate=True) 
  File "/usr/local/lib/python2.6/dist-packages/Amara-2.0a4-py2.6-linux- 
x86_64.egg/amara/tree.py", line 50, in parse 
    return _parse(inputsource(obj, uri), flags, 
entity_factory=entity_factory) 
amara.ReaderError: In file:///home/g/test.xml, line 2, column 0: 
Missing document type declaration 
g@spot:~$ 
=====o===== 

那么,为什么我会看到这个错误?不支持此功能吗?如何在灵活指向任何 XSD 文件的同时针对 XSD 验证 XML 文件?谢谢,如果您有任何问题,请告诉我。

4

2 回答 2

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
于 2010-10-09T16:55:02.840 回答
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.parseXML 文件的解析 ( ) 期间自动找到。

于 2010-10-13T12:53:47.780 回答