在 lxml 中查找元素结束标记的行号

Finding the line number of the element's ending tag in lxml

在使用 lxml 解析 XML 文档时,我想找到特定标记的起始行号和结束行号。我可以通过在 lxml.etree.Element 上使用 sourceline 属性 找到起始标签的位置,但是我很难找到结束标签的行号。

我尝试的一个小例子:

import lxml.etree as ET

xml_sample = b'''<?xml version="1.0" encoding="utf-8"?>
<collection>
    <item>
        <value>foo</value>
    </item>
    <item>
        <value>
            bar
        </value>
    </item>
</collection>'''

for el in ET.fromstring(xml_sample).getroottree().findall('//value'):
    print('Found value "{el.text}" starting on line {el.sourceline} '
          'and ending on line ???.'.format(el=el))

是否可以获取上述示例中value元素的结束标记行号?

使用xml.etree.ElementTree.tostring()技巧:

...
root = ET.fromstring(xml_sample)
for el in root.findall('.//value'):
    endline_num = el.sourceline + (len(ET.tostring(el).strip().split()) - 1)
    print('Found value "{el.text}" starting on line {el.sourceline} '
          'and ending on line {end_num}.'.format(el=el, end_num=endline_num))

输出:

Found value "foo" starting on line 4 and ending on line 4.
Found value "
            bar
        " starting on line 7 and ending on line 9.