使用lxml xml架构验证打印回溯

时间:2013-07-30 20:57:01

标签: python python-2.7 lxml elementtree xml-validation

我正在使用lxml包(etree)接受xml架构并使用代码对xml文件进行解析。

from lxml import etree
import traceback
schema_file = 'C:/Users/Romi/Desktop/XML Testing/schema.xsd'

def validate(xmlparser, xmlfilename):
try:
    with open(xmlfilename, 'r') as f:
        etree.fromstring(f.read(), xmlparser) 
    return True
except:
    return False

with open(schema_file, 'r') as f:
schema_root = etree.XML(f.read())

schema = etree.XMLSchema(schema_root)
xmlparser = etree.XMLParser(schema=schema)

filenames = ['C:/Users/Romi/Desktop/XML Testing/feed.xml','C:/Users/Romi/Desktop/XML          Testing/feed1.xml' ]
fo = open("C:/Users/Romi/Desktop/XML Testing/result.txt", "r+") 
for filename in filenames:
if validate(xmlparser, filename):
    print "%s validates with the schema." % filename
    #fo.write("%s validates with the schema." % filename)
else:
    print "%s doesn't validate with the schema." % filename
    #fo.write("%s doesn't validate with the schema." % filename)

我没有验证时打印错误,但是我想要打印整个回溯,指向它失败的地方,准确地给出错误并转到下一个文件进行验证。

任何指针?

1 个答案:

答案 0 :(得分:2)

您可以使用traceback库在异常捕获中打印出堆栈跟踪:

http://docs.python.org/2/library/traceback.html#traceback-examples

顺便说一句,限制异常处理是一种很好的做法。我改变它所以它只捕获lxml解析错误 - 例如,如果open()失败,你的validate()函数将返回False。

有关这方面的内容:

try:
  with open(xmlfilename, 'r') as f:
    return etree.fromstring(f.read(), xmlparser)
except etree.XMLSyntaxError:
  print traceback.format_exc()

希望有所帮助!