以UTF-8格式从lxml错误日志中打印出消息

时间:2014-04-10 22:08:59

标签: python xml parsing xsd lxml

我学习python(2.7版本),我的任务是使用lxml库(http://lxml.de/)通过xsd schema检查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>

它应该很简单,但我不明白如何使用utx-8的lxml(从不使用编码很难)。我做了简单的步骤:

>>> 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 - 这些只是示例(简短)。对不起我的英语不好。谢谢。

1 个答案:

答案 0 :(得分:3)

您必须使用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"))

<强>结果:

Parse complete!
False
ERROR ON LINE 4: Element 'b': 'Привет мир!' is not a valid value of the atomic type 'xs:decimal'.
[Finished in 1.3s]

可以找到相关文档here

如果有帮助,请告诉我们。