如何将xml xpath解析为列表python
我正在尝试将的值添加到列表中。我需要使用xpath获取一个包含这些值的列表new_values=['a','b']如何将xml xpath解析为列表python,python,xml,xpath,xml-parsing,xml.etree,Python,Xml,Xpath,Xml Parsing,Xml.etree,我正在尝试将的值添加到列表中。我需要使用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> <configu
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>
A.
B
我的python代码的输出是一个只有一个值的列表-['a'],但我需要一个有a和b的列表。您非常接近。您只需使用
findall('events')
并对其进行迭代即可获得所有值
Ex:
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']
['a', 'b']
输出:
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']
['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
元素的xpathevents