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.