如何使用Python中的Amara库根据XSD模式验证xml文件?

2024-10-01 11:27:42 发布

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

对以下问题给予高额奖励:

你好, 下面是我在Ubuntu9.10上使用Python2.6,Amara2 (顺便说一下,测试.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文件的灵活性? 谢谢,如果你有问题请告诉我。在


Tags: pytestechosourcedocparseschemaxml
2条回答

如果您愿意使用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

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

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

文件在哪里测试.xsd在

^{pr2}$

应该放在与测试.xsd. 从XML文件中引用XML模式是一种通用技术,它应该在Python中工作。在

这样做的好处是,不需要知道每个XML文件的模式文件。它将在XML文件的解析(etree.parse)期间自动找到。在

相关问题 更多 >