Sudar Sudar - 1 year ago 330
Python Question

Parsing XML with namespace in Python via 'ElementTree'

I have the following XML which I want to parse using Python's


<rdf:RDF xml:base=""

<owl:Class rdf:about="">
<rdfs:label xml:lang="en">basketball league</rdfs:label>
<rdfs:comment xml:lang="en">
a group of sports teams that compete against each other
in Basketball


I want to find all
tags and then extract the value of all
instances inside them. I am using the following code:

tree = ET.parse("filename")
root = tree.getroot()

Because of the namespace, I am getting the following error.

SyntaxError: prefix 'owl' not found in prefix map

I tried reading the document at but I am still not able to get this working since the above XML has multiple nested namespaces.

Kindly let me know how to change the code to find all the

Answer Source

ElementTree is not too smart about namespaces. You need to give the .find(), findall() and iterfind() methods an explicit namespace dictionary. This is not documented very well:

namespaces = {'owl': ''} # add more as needed

root.findall('owl:Class', namespaces)

Prefixes are only looked up in the namespaces parameter you pass in. This means you can use any namespace prefix you like; the API splits off the owl: part, looks up the corresponding namespace URL in the namespaces dictionary, then changes the search to look for the XPath expression {}Class instead. You can use the same syntax yourself too of course:


If you can switch to the lxml library things are better; that library supports the same ElementTree API, but collects namespaces for you in a .nsmap attribute on elements.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download