簡體   English   中英

Python XML ElementTree標記通配符

[英]Python XML ElementTree tag wildcard

如何在XML TAG搜索中添加通配符? 我正在嘗試使用Python的xml.elementTree庫查找標記為“ MYTAG”的當前XML節點的所有子代。 XML看起來像:

ROOT
   FOO
   BAR
   MYTAG1
   MYTAG2

我試過了

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

使用此方法可以正常工作,但當然只能返回一個元素,不能同時返回兩個元素。

xmlRoot.findall('MYTAG1')

由於xml中xpath的支持相當有限,一種替代方法是使用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')]

結果:

['hello', 'world!']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM