python中xpath使用变量,如何在LXML XPath表达式中使用变量

I'm using Python 3.3 in eclipse with PyDev plugin on Windows 7.

I need to parse an XML file using XPath and LXML. If I use a static XPath expression it works but I need to use a variable one but when I use a variable in the expression it doesn't work.

If I use this code:

xml = etree.parse(fullpath).getroot()

tree = etree.ElementTree(xml)

nsmap = {'xis' : 'http://www.xchanging.com/ACORD4ALLEDI/1',

'ns' : 'http://www.ACORD.org/standards/Jv-Ins-Reinsurance/1' }

p = tree.xpath('//xis:Line', namespaces=nsmap)

print (p)

for e in p:

print(e.tag, e.text)

it works as I want, the print(p) returns

[]

but if I change it to:

xml = etree.parse(fullpath).getroot()

tree = etree.ElementTree(xml)

nsmap = {'xis' : 'http://www.xchanging.com/ACORD4ALLEDI/1',

'ns' : 'http://www.ACORD.org/standards/Jv-Ins-Reinsurance/1' }

header = 'Jv-Ins-Reinsurance'

ns = 'xis:'

path = "'//" + ns + header + "'"

p = tree.xpath('%s' % path, namespaces=nsmap)

print ('p = %s' % p)

for e in p:

print(e.tag, e.text)

the print(p) returns:

p = //xis:Jv-Ins-Reinsurance

and I get an error:AttributeError: 'str' object has no attribute 'tag'.

How can I do this?

Thanks

解决方案

Can you try to remove the single quotes ? I think you have one level too much of quoting in your path variable. I would just use path = "//" + ns + header.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值