Diederik
Diederik

Reputation: 93

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

I'm trying to use XPath expressions using Python's ElementTree. I'm having difficulty extracting parent elements whos chilrens has a specific attribute value. These are not in the examples here, and I also tried this, this doesn't work.

My XML doc looks as follows:

<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>

I'm trying to select all Transaction elements whos Project has an code of "abc".

I defined my root as follows:

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

This works (which returns all Transaction elements which have a Project as a child):

transactions.findall("Transaction[Project]")

This also works (which returns all Project elements which have the code of "abc"):

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

However I'm kind of lost on how to combine these (to get the Transaction elements whos child Project has a specific code). This doesn't work:

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

Nor this (which is discussed here):

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

I have already spend more than 4 hours trying to solve this problem :(. If anyone is able to answer this question for me that would be very helpful!

Kind regards,

Diederik

Upvotes: 2

Views: 1619

Answers (1)

alecxe
alecxe

Reputation: 473863

If you are using (or if you would switch to) lxml.etree and would use the .xpath() method, then your expression would work as is:

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

Upvotes: 2

Related Questions