gpt4 book ai didi

python - 如何使用 Python 中的 Amara 库针对 XSD 模式验证 xml 文件?

转载 作者:太空狗 更新时间:2023-10-30 01:03:55 24 4
gpt4 key购买 nike

以下问题的高赏金:

您好,这是我在 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 的同时验证 XML 文件灵活指向任何 XSD 文件?谢谢,如果您有任何问题,请告诉我。

最佳答案

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

关于python - 如何使用 Python 中的 Amara 库针对 XSD 模式验证 xml 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3330366/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com