Python XML ElementTree标记通配符

2024-07-05 08:27:49 发布

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

如何向xml标记搜索添加通配符? 我试图使用Python的xml.elementTree图书馆。 XML看起来像:

ROOT
   FOO
   BAR
   MYTAG1
   MYTAG2

我试过了

^{pr2}$

使用此方法可以正常工作,但当然只返回一个元素,而不是两个元素。在

xmlRoot.findall('MYTAG1')

Tags: 方法标记元素图书馆foobarrootxml
1条回答
网友
1楼 · 发布于 2024-07-05 08:27:49

由于xpath支持在xml中相当有限,一种替代方法是使用getchildren()并返回带有标记startswith的节点:

import xml.etree.ElementTree as ET
from StringIO import StringIO

# sample xml
s = '<root><mytag1>hello</mytag1><mytag2>world!</mytag2><tag3>nothing</tag3></root>'
tree = ET.parse(StringIO(s))
root = tree.getroot()
# using getchildren() within root and check if tag starts with keyword 
print [node.text for node in root.getchildren() if node.tag.startswith('mytag')]

结果:

^{pr2}$

相关问题 更多 >