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

时间:2017-12-20 09:20:43

标签: python lxml

在使用lxml解析XML文档时,我想查找特定标记的起始行和结束行号。我可以使用sourceline上的lxml.etree.Element属性找到起始标记的位置,但我正在努力寻找结束标记的行号。

我尝试的一个小例子:

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元素的结束标记行号?

1 个答案:

答案 0 :(得分:4)

使用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.