如果特定属性匹配,则查找并提取 xml 标签的名称

Find and extract the name of xml tag if specific attribute is matching

如果该列标记在 name 属性中具有 (group) 字符串,我想提取标记的名称 column。我通过堆栈进行了研究,发现了一些提示,但是遵循这些提示并没有得到答案。更多信息如下。

示例XML:

<datas>
    <data>
      <column datatype='real' default-format='c&quot;$&quot;#,##0;(&quot;$&quot;#,##0)' name='[Sales]' role='measure' type='quantitative' />
      <column datatype='real' default-format='c&quot;$&quot;#,##0;(&quot;$&quot;#,##0)' name='[Shipping Cost]' role='measure' type='quantitative' />
      <column datatype='string' name='[State]' role='dimension' semantic-role='[State].[Name]' type='nominal' />
      <column datatype='string' name='[Sub-Category (group)]' role='dimension' type='nominal'>
    </data>
</datas>

我的尝试:

#USING ELEMTREE, python3 to parse xml
columnfind = twbroot.findall('./datas/data')
for i in columnfind:
    select= i.("//*[contains(@name,'(group)')]")

xml.etree模块只支持XPath 1.0的limited subset,不包含contains()。所以你需要做 'contains' 检查 python:

columnfind = twbroot.findall('data/column')
for col in columnfind:
    if '(group)' in col.get('name'):
        print col.get('name')

或者:

cols = [e.get('name') for e in root.findall("data/column") if '(group)' in e.get('name')]
print(cols)

eval.in demo

如果您有能力使用 lxml,它具有完整的 XPath 1.0 支持,因此您可以直接在 XPath 中进行检查:

cols = [e.get('name') for e in root.xpath("data/column[contains(@name,'(group)')]")]
print(cols)