[英]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. 我正在尝试通过Python的ElementTree使用XPath表达式。 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: 我的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>
I'm trying to select all Transaction elements whos Project has an code of "abc". 我正在尝试选择所有交易元素,而谁的项目的代码为“ 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): 这有效(返回所有将Project作为子项的Transaction元素):
transactions.findall("Transaction[Project]")
This also works (which returns all Project elements which have the code of "abc"): 这也起作用(返回所有代码为“ abc”的Project元素):
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). 但是,我对如何将它们组合在一起(让子项目Project具有特定代码的Transaction元素)迷失了。 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! 我已经花费了4个多小时来尝试解决此问题:(。如果有人能够为我回答这个问题,那将非常有帮助!
Kind regards, 亲切的问候,
Diederik Diederik
如果您正在使用(或如果要切换到) lxml.etree
并使用.xpath()
方法,则表达式将按以下方式工作:
transactions.xpath("Transaction[Project[@code='abc']]")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.