在 Python 中使用 elementree xpath 在子元素具有特定属性值时选择父元素

Selecting parent element when child has a specific value of attribute using elementree xpath in Python

我正在尝试使用 Python 的 ElementTree 来使用 XPath 表达式。我很难提取子元素具有特定属性值的父元素。这些不在示例中 here, and I also tried this,这不起作用。

我的 XML 文档如下所示:

<Transactions>
<Transaction>
    <Project code="abc">
        <Description>blah blah</Description>
        <StartDate>2014-10-02</StartDate>
    </Project>
    <Quantity>100</Quantity>
    <Price>
        <Currency code="EUR" />
        <Value>100</Value>
    </Price>
</Transaction>
<Transaction>
    <Project code="def">
        <Description>something else</Description>
        <StartDate>2014-10-12</StartDate>
    </Project>
    <Quantity>4</Quantity>
    <Price>
        <Currency code="EUR" />
        <Value>2</Value>
    </Price>
</Transaction>
<Transaction>
    <Project code="abc">
        <Description>blah blah</Description>
        <StartDate>2014-11-02</StartDate>
    </Project>
    <Quantity>1</Quantity>
    <Price>
        <Currency code="EUR" />
        <Value>123</Value>
    </Price>
</Transaction></Transactions>

我正在尝试 select 项目代码为 "abc" 的所有事务元素。

我的根定义如下:

transactions = ET.parse('../doc.xml').getroot();

这有效(returns 所有将项目作为子项的事务元素):

transactions.findall("Transaction[Project]")

这也有效(returns 所有代码为 "abc" 的项目元素):

transactions.findall(".//Project[@code='abc']")

但是我有点迷失了如何组合这些(以获取子项目具有特定代码的事务元素)。这不起作用:

transactions.findall("Transaction[Project[@code='abc']]")

也不是这个(讨论here):

transactions.findall("Transaction[Project/@code='abc']")

我已经花了 4 个多小时来解决这个问题:(。如果有人能够为我回答这个问题,那将非常有帮助!

亲切的问候,

迪德里克

如果您正在使用(或者如果您将切换到)lxml.etree 并且将使用 .xpath() 方法,那么您的表达式将按原样工作:

transactions.xpath("Transaction[Project[@code='abc']]")