如何将 xml xpath 解析为列表 python
How to parse xml xpath into list python
我正在尝试将 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 的列表。
你很接近。您只需要使用 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']
针对单个 .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']
我正在尝试将 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 的列表。
你很接近。您只需要使用 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']
针对单个 .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']