dmg*_*mgl 2 python xml parsing xsd lxml
我学习python(2.7版本),我有任务使用lxml库(http://lxml.de/)通过xsd模式检查xml文档。我有两个文件 - 像这样的例子:
$ cat 1.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE yml_catalog SYSTEM "shops.dtd">
<a>
<b>?????? ???!</b>
</a>
Run Code Online (Sandbox Code Playgroud)
和
$cat 2.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xs:element name="a" type="AType"/>
<xs:complexType name="AType">
<xs:sequence>
<xs:element name="b" type="xs:decimal" />
</xs:sequence>
</xs:complexType>
</xs:schema>
Run Code Online (Sandbox Code Playgroud)
它应该非常简单,但我不明白如何将 lxml 与 utf-8 一起使用(从不使用硬编码)。我做简单的步骤:
>>> from lxml import etree
>>> schema = etree.parse("/tmp/qwerty/2.xsd")
>>> xmlschema = etree.XMLSchema(schema)
>>> try:
document = etree.parse("/tmp/qwerty/1.xml")
print "Parse complete!"
except etree.XMLSyntaxError, e:
print e
Parse complete!
>>> xmlschema.validate(document)
False
>>> xmlschema.error_log
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
xmlschema.error_log
File "xmlerror.pxi", line 286, in lxml.etree._ListErrorLog.__repr__ (src/lxml/lxml.etree.c:33216)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 85-90: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
而且我无法从 .error_log 中获取所有引发的异常。
有任何使用编码/解码方法的解决方法来检查它(成功)或者解决方案(并且没有另一个库(我谈论标准的python方法)),或者我可能需要使用StringIO(但如何)?
我知道我的问题源于“?????? ???!” 和 xs:decimal - 这些只是示例(简短)。对不起我的英语不好。谢谢你。
您必须使用 对错误日志中的错误消息进行编码utf-8
。请尝试以下操作:
代码:
from lxml import etree
schema = etree.parse("2.xsd")
xmlschema = etree.XMLSchema(schema)
try:
document = etree.parse("1.xml")
print "Parse complete!"
except etree.XMLSyntaxError, e:
print e
print xmlschema.validate(document)
for error in xmlschema.error_log:
print "ERROR ON LINE %s: %s" % (error.line, error.message.encode("utf-8"))
Run Code Online (Sandbox Code Playgroud)
结果:
Parse complete!
False
ERROR ON LINE 4: Element 'b': '?????? ???!' is not a valid value of the atomic type 'xs:decimal'.
[Finished in 1.3s]
Run Code Online (Sandbox Code Playgroud)
相关文档可以在这里找到。
如果这有帮助,请告诉我们。
归档时间: |
|
查看次数: |
2167 次 |
最近记录: |