我在eclipse中使用python3.3和windows7上的PyDev插件。在
我需要使用XPath和LXML解析XML文件。如果我使用静态XPath表达式,它可以工作,但我需要使用一个变量,但当我在表达式中使用变量时,它就不起作用了。在
如果我使用这个代码:
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)
返回
但如果我把它改成:
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
。在您正在构建一个带有文字引号的字符串。您不需要省略
'
字符。在或使用字符串格式:
^{pr2}$您的原始版本相当于:
(注意额外的单引号字符)。在
相关问题 更多 >
编程相关推荐