2

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

1 Answer 1

2

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']]")
Sign up to request clarification or add additional context in comments.

1 Comment

Wow! I just switched from xml.etree.ElementTree to lxml.etree. Not only do my xpath expressions now work, it is also literally ten times faster!! Thank you alecxe!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.