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

2024-01-13

在使用 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上面例子中的元素?


With xml.etree.ElementTree.tostring() trick:

...
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.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在lxml中查找元素结束标记的行号 的相关文章

随机推荐