python lxml findall with multiple namespaces

我的未来我决定 提交于 2019-12-01 21:42:37

If you start with this:

>>> tree = etree.parse(open('data.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 findall and find methods require {...namespace...}ElementName syntax.
  • The xpath method requires namespace prefixes (ns:ElementName), which it looks up in the provided namespaces map. 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>]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!