python - 在 ElementTree/Python 中使用多个属性查找事件

标签 python xml elementtree

我有以下 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>

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

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

最佳答案

这取决于您使用的版本。如果您有 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']

关于python - 在 ElementTree/Python 中使用多个属性查找事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4808753/

相关文章:

python - 解析 XML 异常

python - 使用 namespace 解析 XML

python-3.x - 有没有办法使用 ElementTree 注册多个命名空间

java - java 9 上的 jaxb2-maven-plugin 失败

python - 解析 XML 文件并根据 xsd 架构进行验证

html - 如何在 Jupyter (R) 中呈现 LaTeX/HTML?

python - 使用 pd.read_clipboard 读取打印精美/格式化的数据框?

python - __init__() 缺少 3 个必需的位置参数

python - 如何使用列中的值来确定要在不同数据框中分析哪一列?

python - 为什么我的列表是 Nonetype?在 python