ElementTree findall'or'运算符 [英] ElementTree findall 'or' operator

查看:99
本文介绍了ElementTree findall'or'运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的xml文件:

If I have an xml file like this:

<root>
  <item>
    <prop>something</prop>
  </item>
  <test>
    <prop>something</prop>
  </test>
  <test2>
    <prop>something</prop>
  </test2>
</root>

我可以使用
xmlTree.getroot()。findall( item)
来获取所有 item元素。

I can use xmlTree.getroot().findall("item") to get all of the 'item' elements.

我如何获取所有的 item或 test元素?我想要类似的东西:

How would I get all of the 'item' OR 'test' elements? I want something like:

xmlTree.getroot()。findall( item or test)

我在文档的示例中没有看到类似的内容。有任何想法吗?

I didn't see anything like this in the examples in the documentation. Any ideas?

推荐答案

因为 ElementTree 仅提供有限的xpath支持,您可以使用 | xpath OR运算符,仅当您使用 lxml

Since ElementTree from stdlib provides only limited xpath support, you can use | xpath OR operator only if you are using lxml:

from lxml import etree as ET


data = """<?xml version="1.0"?>
<data>
<item>1</item>
<test>2</test>
</data>"""

tree = ET.fromstring(data)

for element in tree.xpath('//item|//test'):
    print element.text

打印:

1
2

对于 xml.etree.ElementTree ,您可以将两个单独的 findall()调用:

In case of xml.etree.ElementTree you can combine the results of two separate findall() calls:

for element in tree.findall('.//item') + tree.findall('.//test'):
    print element.text

或者,检查循环中的标签名称:

Or, check the tag name inside the loop:

for element in tree.iter():
    if element.tag in ('item', 'test'):
        print element.text

这篇关于ElementTree findall'or'运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆