gpt4 book ai didi

Python 没有捕获 XMLSyntaxError

转载 作者:太空宇宙 更新时间:2023-11-03 19:31:29 24 4
gpt4 key购买 nike

我有以下 python + lxml 代码:

def doXMLValidation (xml_file, schema_file):
'''Validates xml file against schema'''
s_doc = etree.parse (schema_file)
schema = etree.XMLSchema (s_doc)
x_file = etree.parse(xml_file)

try:
schema.assertValid(x_file)
except etree.XMLSyntaxError as e:
print (_formatXMLError(e))
return False
except etree.DocumentInvalid as e:
print (_formatXMLError(e))
return False
except:
print ('Something strange...')
return False
else:
return True

当我尝试使用损坏的 xml/fb2 文件(标记已删除)对其进行测试时,我希望通过正确的处理得到 XMLSyntaxError 异常。但是,我却因该错误而崩溃:

../.metadata/.plugins/org.python.pydev.debug/.coverage Traceback (most recent call last):
File "../.eclipse/org.eclipse.platform_3.5.0_155965261/plugins/org.python.pydev.debug_1.5.9.2010063001/pysrc/coverage.py", line 1029, in the_coverage.command_line(sys.argv[1:]) File "../.eclipse/org.eclipse.platform_3.5.0_155965261/plugins/org.python.pydev.debug_1.5.9.2010063001/pysrc/coverage.py", line 405, in command_line execfile(sys.argv[0], main._dict_) File "../workspace/PythonPractice/src/lxmlValidation.py", line 58, in test() File "../workspace/PythonPractice/src/lxmlValidation.py", line 54, in test result = doXMLValidation (source, schema) File "../workspace/PythonPractice/src/lxmlValidation.py", line 31, in doXMLValidation x_file = etree.parse(xml_file) File "lxml.etree.pyx", line 2692, in lxml.etree.parse (src/lxml/lxml.etree.c:49594) File "parser.pxi", line 1500, in lxml.etree._parseDocument (src/lxml/lxml.etree.c:71364) File "parser.pxi", line 1529, in lxml.etree._parseDocumentFromURL (src/lxml/lxml.etree.c:71647) File "parser.pxi", line 1429, in lxml.etree._parseDocFromFile (src/lxml/lxml.etree.c:70742) File "parser.pxi", line 975, in lxml.etree._BaseParser._parseDocFromFile (src/lxml/lxml.etree.c:67740) File "parser.pxi", line 539, in lxml.etree._ParserContext._handleParseResultDoc (src/lxml/lxml.etree.c:63824) File "parser.pxi", line 625, in lxml.etree._handleParseResult (src/lxml/lxml.etree.c:64745) File "parser.pxi", line 565, in lxml.etree._raiseParseError (src/lxml/lxml.etree.c:64088) lxml.etree.XMLSyntaxError: Opening and ending tag mismatch: a line 7 and p, line 7, column 46

问题可能是什么以及如何解决?

UPD:哈哈,明白了,谢谢大家:

def doXMLValidation (xml_file, schema_file):
'''Validates xml file against schema'''
s_doc = etree.parse (schema_file)
schema = etree.XMLSchema (s_doc)
try:
x_file = etree.parse(xml_file)
schema.assertValid(x_file)
except etree.XMLSyntaxError as e:
print (_formatXMLError(e))
return False
except etree.DocumentInvalid as e:
print (_formatXMLError(e))
return False
except:
print ('Something strange...')
return False
else:
return True

认为解析时 lxml 会更容易接受...

最佳答案

在导致错误的语句之前没有尝试。更仔细地查看堆栈跟踪。

关于Python 没有捕获 XMLSyntaxError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5610043/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com