python如何知道xm中哪个标签没有关闭

2024-05-29 10:10:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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'

Tags: ofselfformatmessageinit错误exceptionposition
2条回答

这可能不是您想要的,但您可以从异常中获得检测到错误的确切行和列:

import lxml.etree
import StringIO
xml_fragment = "<name>Marco</name1>"
#               12345678901234
try:
    lxml.etree.parse(StringIO.StringIO(xml_fragment))
except lxml.etree.XMLSyntaxError as exc:
    line, column = exc.position

在本例中,linecolumn将是1和14,这表示结束标记的第一个字符没有匹配的开始标记。你知道吗

您可以打印错误的详细信息。例如:

try:
    self.doc = etree.parse(attributesXMLFilePath)
except XMLSyntaxError as e:
    error_message = "The file {0} is not correct XML, {1}".format(attributesXMLFilePath, e.msg)
    raise NotGoodXMLFormatException(error_message)

相关问题 更多 >

    热门问题