【问题标题】:How to parse xml xpath into list python如何将xml xpath解析为list python
【发布时间】:2019-06-27 09:44:36
【问题描述】:

我正在尝试将 in 的值添加到列表中。我需要使用 xpath 获取包含此值 new_values = ['a','b'] 的列表

import xml.etree.ElementTree as ET
parse = ET.parse('xml.xml')
[ record.find('events').text for record in parse.findall('.configuration/system/') ]

xml.xml 文件

<rpc-reply>
    <configuration>
            <system>
                <preference>
                    <events>a</events>
                    <events>b</events>                    
                </preference>
            </system>
    </configuration>
</rpc-reply>

我的 python 代码的输出是一个只有一个值的列表 - ['a'],但我需要一个带有 a 和 b 的列表。

【问题讨论】:

    标签: python xml xpath xml-parsing xml.etree


    【解决方案1】:

    优化为单个.findall() 调用:

    import xml.etree.ElementTree as ET
    
    root = ET.parse('input.xml').getroot()
    events = [e.text for e in root.findall('configuration/system//events')]
    
    print(events)
    
    • configuration/system//events - events 元素的相对 xpath

    输出:

    ['a', 'b']
    

    【讨论】:

      【解决方案2】:

      你已经很接近了。您只需要使用findall('events') 并对其进行迭代以获取所有值。

      例如:

      import xml.etree.ElementTree as ET
      parse = ET.parse('xml.xml')
      print([ events.text for record in parse.findall('.configuration/system/') for events in record.findall('events')])
      

      输出:

      ['a', 'b']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-10
        • 1970-01-01
        • 1970-01-01
        • 2012-03-27
        相关资源
        最近更新 更多