[英]xpath-expression works with literal but not with variable
I have an XML file containing data looking as follows:我有一个 XML 文件,其中包含如下数据:
<?xml version="1.0" encoding="UTF-8"?>
<document date="2021-03-01" name="dataExport">
<CASHFLOW CASHFLOW_ID="001" C001="06-08"/><CASHFLOW_FIELD CASHFLOW_ID="001" C001="06-08" FIELDNAME="A001" VALUE="0"/><CASHFLOW_FIELD CASHFLOW_ID="001" F001="04-08-01" FIELDNAME="C254" VALUE="15.78"/>
<CASHFLOW CASHFLOW_ID="002" C001="06-08"/><CASHFLOW_FIELD CASHFLOW_ID="001" C001="06-08" FIELDNAME="A001" VALUE="2"/><CASHFLOW_FIELD CASHFLOW_ID="002" C001="06-08" FIELDNAME="C254" VALUE="10.55"/>
</document>
Using XPath, I want - for each entry - to get the value of attribute "VALUE" where attribute "FIELDNAME" has value "C254".使用 XPath,我希望 - 对于每个条目 - 获取属性“VALUE”的值,其中属性“FIELDNAME”的值为“C254”。
I tried the following to achieve my goal (using python library lxml):我尝试了以下方法来实现我的目标(使用 python 库 lxml):
import lxml.etree as etree
global tree
tree = etree.parse('filepath/filename.xml')
cashflow_ids = tree.xpath("//CASHFLOW/@CASHFLOW_ID")
for cashflow_id in cashflow_ids:
print(cashflow_id)
value_I_want = tree.xpath("//CASHFLOW_FIELD[@CASHFLOW_ID=cashflow_id and @FIELDNAME='C254']/@VALUE")
print(value_I_want)
Unfortunately, with this code value_I_want equals an empty list in each case.不幸的是,使用此代码 value_I_want 在每种情况下都等于一个空列表。
The problem is the variable "cashflow_id".问题是变量“cashflow_id”。
If I execute the code for a specific value, it works.如果我为特定值执行代码,它就可以工作。 For example, the following works fine:
例如,以下工作正常:
value_I_want = tree.xpath("//CASHFLOW_FIELD[@CASHFLOW_ID='002' and @FIELDNAME='C254']/@VALUE")
(value_I_want in this case equals 10.55) (在这种情况下,value_I_want 等于 10.55)
How can I make the code work with a variable instead of a literal?如何使代码使用变量而不是文字?
You're passing in the string cashflow_id
whereas you want to have the value, convert it to a f-string and pass in the variable cashflow_id
like this and it works:您正在传递字符串
cashflow_id
而您想要获得该值,将其转换为 f 字符串并像这样传递变量cashflow_id
并且它可以工作:
value_I_want = tree.xpath(f"//CASHFLOW_FIELD[@CASHFLOW_ID={cashflow_id} and @FIELDNAME='C254']/@VALUE")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.