【问题标题】:Finding the line number of the element's ending tag in lxml在lxml中查找元素结束标记的行号
【发布时间】:2018-06-02 19:21:41
【问题描述】:

在使用 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元素的结束标记行号是否可以获取?

【问题讨论】:

    标签: python lxml


    【解决方案1】:

    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.
    

    【讨论】:

      猜你喜欢
      • 2013-03-11
      • 2011-04-05
      • 1970-01-01
      • 2021-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-07
      • 1970-01-01
      相关资源
      最近更新 更多