4

I have a valid XHTML file. When I do

import xml.etree.ElementTree as ET
print ET._namespace_map

it lists:

'http://www.w3.org/1999/xhtml': 'html'

When I do:

root.find('{http://www.w3.org/1999/xhtml}head')

it finds:

<Element '{http://www.w3.org/1999/xhtml}head' at 0x104647168>

But when I do:

root.find('html:head')

it complains:

SyntaxError: prefix 'html' not found in prefix map

Is it possible to find an name-spaced-element with find using the syntax ns:element?

Ecir Hana
  • 10,864
  • 13
  • 67
  • 117

1 Answers1

5

You should specify namespaces argument:

namespaces = {'html': 'http://www.w3.org/1999/xhtml'}
root.find('html:head', namespaces=namespaces)

Also see:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Ok, it works, thanks! But what is then the `register_namespace` or `_namespace_map` good for? – Ecir Hana Mar 31 '14 at 15:00
  • @EcirHana `register_namespace()` is essentially a new way (elementtree>=1.3) of manipulating `_namespace_map`, see what are they good for [here](http://effbot.org/zone/element-namespaces.htm). Hope that helps. – alecxe Mar 31 '14 at 15:07