Python 在xml etree解析中使用正则表达式

Python 在xml etree解析中使用正则表达式,python,xml,xpath,xml-parsing,Python,Xml,Xpath,Xml Parsing,我需要解析xml文件并找到一个仅以“123”开头的值。 我如何使用下面的代码做到这一点? 是否可以在此语法中使用正则表达式 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')]) xml.xml &

我需要解析xml文件并找到一个仅以“123”开头的值。 我如何使用下面的代码做到这一点? 是否可以在此语法中使用正则表达式

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')])
xml.xml

<rpc-reply>
 <configuration>
        <system>
            <preference>
                <events>123</events>
                <events>124</events>
                <events>1235</events>                    
            </preference>
        </system>
 </configuration>
</rpc-reply>

123
124
1235

使用内置函数
start-with()
XPath谓词可以做很多事情。但您需要使用完全支持XPath 1.0的库,例如:


对于regex来说,最好是对未解析(字符串)的xml进行操作-只需获取
re.findall(r'>(123[^@h4z3)是的,但是,如果我只在标记或其他标记中找到这些值会怎么样?请阅读
ET.findall
中的XPath使用。XPath可以进行此类过滤,但您需要测试您到底想要什么。(只需在互动控制台中玩它。我需要特定的东西时会这样做。)
from lxml import etree as ET
raw = '''<rpc-reply>
 <configuration>
        <system>
            <preference>
                <events>123</events>
                <events>124</events>
                <events>1235</events>                    
            </preference>
        </system>
 </configuration>
</rpc-reply>'''
root = ET.fromstring(raw)
query = 'configuration/system/preference/events[starts-with(.,"123")]'
print([events.text for events in root.xpath(query)])
....
query = 'configuration/system/preference/events'
print([events.text for events in root.findall(query) if events.text.startswith('123')])