如何在LXML XPath表达式中使用变量 [英] How to use a variable in LXML XPath Expression

查看:162
本文介绍了如何在LXML XPath表达式中使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Windows 7上的Eclipse中使用带有PyDev插件的Python 3.3.

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

我需要使用XPath和LXML解析XML文件.如果我使用静态XPath表达式,则可以使用,但是我需要使用一个变量,但是当我在表达式中使用变量时,则无法使用.

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.

如果我使用此代码:

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)

它可以按我的要求工作,print(p)返回

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

 [<Element {http://www.xchanging.com/ACORD4ALLEDI/1}LloydsProcessingCode at 0x2730350>]

但是如果我将其更改为:

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)

print(p)返回:

p = //xis:Jv-Ins-Reinsurance

我收到一个错误:AttributeError: 'str' object has no attribute 'tag'.

我该怎么做?

谢谢

推荐答案

可以尝试删除单引号吗?我认为您在path变量中引用过多了.我只会用path = "//" + ns + header.

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.

这篇关于如何在LXML XPath表达式中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆