我有一个xml,我验证它是否真的是一个格式良好的xml,如下所示:
try:
self.doc=etree.parse(attributesXMLFilePath)
except IOError:
error_message = "Error: Couldn't find attribute XML file path {0}".format(attributesXMLFilePath)
raise XMLFileNotFoundException(error_message)
except XMLSyntaxError:
error_message = "The file {0} is not a good XML file, recheck please".format(attributesXMLFilePath)
raise NotGoodXMLFormatException(error_message)
如您所见,我正在捕获XMLSyntaxError,这是一个错误,来自:
from lxml.etree import XMLSyntaxError
这很好,但它只是告诉我,如果文件不是一个好的xml格式。但是,我想问你们是否有办法知道哪个标签错了,因为在我这样做的时候:
<name>Marco</name1>
我得到了错误,有没有办法知道name
标签还没有关闭?你知道吗
在一些人给了我线条和位置的概念之后,我想到了以下代码:
class XMLFileNotFoundException(GeneralSpiderException):
def __init__(self, message):
super(XMLFileNotFoundException, self).__init__(message, self)
class GeneralSpiderException(Exception):
def __init__(self, message, e):
super(GeneralSpiderException, self).__init__(message+" \nline of Exception = {0}, position of Exception = {1}".format(e.lineno, e.position))
我仍然像这样提出错误
raise XMLFileNotFoundException(error_message)
我现在犯了这个错误
super(GeneralSpiderException, self).__init__(message+" \nline of Exception = {0}, position of Exception = {1}".format(e.lineno, e.position))
exceptions.AttributeError: 'XMLFileNotFoundException' object has no attribute 'lineno'
这可能不是您想要的,但您可以从异常中获得检测到错误的确切行和列:
在本例中,
line
和column
将是1和14,这表示结束标记的第一个字符没有匹配的开始标记。你知道吗您可以打印错误的详细信息。例如:
相关问题 更多 >
编程相关推荐