Python XML ElementTree tag wildcard

How do I add a wildcard to xml TAG search? I'm trying to find all children of the current XML node who's tag starts with "MYTAG" using Python's xml.elementTree library. XML Looks like:

ROOT
   FOO
   BAR
   MYTAG1
   MYTAG2

I've tried

xmlTree = xmlET.parse('XML_FILE')
xmlRoot = xmlTree.getroot()
MYTags = xmlRoot.findall('MYTAG{*}')

Using this works correctly but of course only returns one element, not both.

xmlRoot.findall('MYTAG1')

As the xpath supports are rather limited in xml , one alternative is to use getchildren() and return the node with tag 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')]

Results:

['hello', 'world!']
链接地址: http://www.djcxy.com/p/58802.html

上一篇: 使用lxml从xml中提取嵌套名称空间

下一篇: Python XML ElementTree标记通配符