xml - Selecting parent element when child has a specific value of attribute using elementree xpath in Python -
i'm trying use xpath expressions using python's elementtree. i'm having difficulty extracting parent elements whos chilrens has specific attribute value. these not in examples here, , tried this, doesn't work.
my xml doc looks 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 select transaction elements whos project has code of "abc".
i defined root follows:
transactions = et.parse('../doc.xml').getroot();
this works (which returns transaction elements have project child):
transactions.findall("transaction[project]")
this works (which returns project elements have code of "abc"):
transactions.findall(".//project[@code='abc']")
however i'm kind of lost on how combine these (to transaction elements whos child project has specific code). doesn't work:
transactions.findall("transaction[project[@code='abc']]")
nor (which discussed here):
transactions.findall("transaction[project/@code='abc']")
i have spend more 4 hours trying solve problem :(. if able answer question me helpful!
kind regards,
diederik
if using (or if switch to) lxml.etree
, use .xpath()
method, expression work is:
transactions.xpath("transaction[project[@code='abc']]")
Comments
Post a Comment