我正在使用 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)
我在未验证时打印错误,但我想打印指向失败位置的整个回溯,准确给出错误并转到下一个文件进行验证。
任何指针?