在lxml中查找元素的结束标记的行号 [英] Finding the line number of the element's ending tag in lxml

查看:104
本文介绍了在lxml中查找元素的结束标记的行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

While parsing an XML document with lxml I want to find the starting and ending line numbers of a particular tag. I am able to find the starting tag's position by using the sourceline property on lxml.etree.Element, however I am struggling at finding the closing tag's line number.

我尝试的一个简单例子:

A trivial example of my attempt:

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

Is it possible to get the closing tag line numbers of the value elements in the above example?

推荐答案

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

这篇关于在lxml中查找元素的结束标记的行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆