【发布时间】:2014-05-24 20:46:38
【问题描述】:
我学习 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>
和
$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>
它应该很简单,但我不明白如何将 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)
而且我无法从 .error_log 中获取所有引发的异常。
有任何使用编码/解码方法的解决方法来检查它(成功)或者解决方案(并且没有另一个库(我谈论标准python方法)),或者我需要使用StringIO(但是如何)?
我知道我的问题在于“Привет мир!”和 xs:decimal - 这些只是示例(简短)。对不起我的英语不好。谢谢。
【问题讨论】:
-
使用另一种语言和字符串“Hello world!”,而不是“Привет мир!”没问题:>>> xmlschema.error_log /tmp/qwerty/1.xml:4:0:ERROR:SCHEMASV:SCHEMAV_CVC_DATATYPE_VALID_1_2_1:元素'b':'Hello world!'不是原子类型“xs:decimal”的有效值。
标签: python xml parsing xsd lxml