在lxm中用regex替换字符串

2024-09-29 21:42:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用python2.7、lxml3.7.3和exlst扩展,通过XPath从XML中提取数据。 我可以在测试节点时使用regex扩展,就像lxml documentation 建议的那样。节选:

>>> regexpNS = "http://exslt.org/regular-expressions"
>>> find = etree.XPath("//*[re:test(., '^abc$', 'i')]",
...                    namespaces={'re':regexpNS})

>>> root = etree.XML("<root><a>aB</a><b>aBc</b></root>")   
>>> print(find(root)[0].text)
aBc

我希望使用xpath表达式只生成node text()的子字符串。 我该怎么做?在


Tags: 数据textre节点documentationrootxmlfind
1条回答
网友
1楼 · 发布于 2024-09-29 21:42:35

要在这里使用xpath表达式,可以

import xml.etree.ElementTree as ET
root = ET.fromstring("<root><a>aB</a><b>aBc</b></root>")

for item in root.findall(".//b"):
    print(item.text)
    # aBc

更多示例请参见他们的documentation page。在

相关问题 更多 >

    热门问题