Python Lxml Findall With Multiple Namespaces
I'm trying to parse an XML document with multiple namespaces with lxml, and I'm stuck on getting the findall() method to return something. My XML: ))
root = tree.getroot()
This will fail to find any elements...
>>> root.findall('{http://www.company.com/common/rsp/2012/07}MeasurementRecords')
[]
...but that's because root is a MeasurementRecords element; it
does not contain any MeasurementRecords elements. On the other
hand, the following works just fine:
>>> root.findall('{http://www.company.com/common/rsp/2012/07}HistoryRecords')
[<Element {http://www.company.com/common/rsp/2012/07}HistoryRecords at 0x7fccd0332ef0>]
>>>
Using the xpath method, you could do something like this:
>>> nsmap={'a': 'http://www.company.com/common/rsp/2012/07',
... 'b': 'http://www.w3.org/2001/XMLSchema-instance'}
>>> root.xpath('//a:HistoryRecords', namespaces=nsmap)
[<Element {http://www.company.com/common/rsp/2012/07}HistoryRecords at 0x7fccd0332ef0>]
So:
- The
findallandfindmethods require{...namespace...}ElementNamesyntax. - The
xpathmethod requires namespace prefixes (ns:ElementName), which it looks up in the providednamespacesmap. The prefix doesn't have to match the prefix used in the original document, but the namespace url must match.
So this works:
>>> root.find('{http://www.company.com/common/rsp/2012/07}HistoryRecords/{http://www.company.com/common/rsp/2012/07}ValueItemId')
<Element {http://www.company.com/common/rsp/2012/07}ValueItemId at 0x7fccd0332a70>
Or this works:
>>> root.xpath('/a:MeasurementRecords/a:HistoryRecords/a:ValueItemId',namespaces=nsmap)
[<Element {http://www.company.com/common/rsp/2012/07}ValueItemId at 0x7fccd0330830>]
Post a Comment for "Python Lxml Findall With Multiple Namespaces"