【问题标题】:Find occurrence using multiple attributes in ElementTree/Python在 ElementTree/Python 中使用多个属性查找事件
【发布时间】:2011-01-26 19:02:58
【问题描述】:

我有以下 XML。

<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="10" failures="0" disabled="0" errors="0" time="0.001" name="AllTests">
  <testsuite name="TestOne" tests="5" failures="0" disabled="0" errors="0" time="0.001">
    <testcase name="DefaultConstructor" status="run" time="0" classname="TestOne" />
    <testcase name="DefaultDestructor" status="run" time="0" classname="TestOne" />
    <testcase name="VHDL_EMIT_Passthrough" status="run" time="0" classname="TestOne" />
    <testcase name="VHDL_BUILD_Passthrough" status="run" time="0" classname="TestOne" />
    <testcase name="VHDL_SIMULATE_Passthrough" status="run" time="0.001" classname="TestOne" />
</testsuite>
</testsuites>

问:如何找到节点&lt;testcase name="VHDL_BUILD_Passthrough" status="run" time="0" classname="TestOne" /&gt;?我找到了函数tree.find(),但这个函数的参数似乎是元素名称。

我需要根据属性找到节点:name = "VHDL_BUILD_Passthrough" AND classname="TestOne"

【问题讨论】:

  • 你的testsuite标签没有关闭?
  • @eumiro :这是一个错字,感谢您指出这一点。

标签: python xml elementtree


【解决方案1】:

这取决于您使用的版本。如果你有 ElementTree 1.3+(包括在 Python 2.7 标准库中),你可以使用基本的 xpath 表达式,如 described in the docs,如 [@attrib='value']

x = ElmentTree(file='testdata.xml')
cases = x.findall(".//testcase[@name='VHDL_BUILD_Passthrough'][@classname='TestOne']")

很遗憾,如果您使用的是 ElementTree 的早期版本(1.2,包含在 python 2.5 和 2.6 的标准库中),您将无法使用这种便利,需要自己进行过滤。

x = ElmentTree(file='testdata.xml')
allcases = x12.findall(".//testcase")
cases = [c for c in allcases if c.get('classname') == 'TestOne' and c.get('name') == 'VHDL_BUILD_Passthrough']

【讨论】:

    【解决方案2】:

    您必须遍历您拥有的 &lt;testcase /&gt; 元素,如下所示:

    from xml.etree import cElementTree as ET
    
    # assume xmlstr contains the xml string as above
    # (after being fixed and validated)
    testsuites = ET.fromstring(xmlstr)
    testsuite = testsuites.find('testsuite')
    for testcase in testsuite.findall('testcase'):
        if testcase.get('name') == 'VHDL_BUILD_Passthrough':
            # do what you will with `testcase`, now it is the element
            # with the sought-after attribute
            print repr(testcase)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-29
      • 1970-01-01
      • 2018-01-05
      • 2016-03-18
      • 2015-07-04
      • 2011-06-02
      相关资源
      最近更新 更多