The Python Oracle

Setting and accessing namespaces in python lxml

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Future Grid Looping

--

Chapters
00:00 Setting And Accessing Namespaces In Python Lxml
01:25 Accepted Answer Score 1
01:46 Thank you

--

Full question
https://stackoverflow.com/questions/4811...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #namespaces #lxml

#avk47



ACCEPTED ANSWER

Score 1


Modifying root.nsmap has no effect. But you can create another dictionary and modify that one. Example:

from lxml import etree

doc = """
<root xmlns:skos="http://www.w3.org/2004/02/skos/core#">
   <skos:prefLabel xml:lang='en'>FOO</skos:prefLabel>
   <skos:prefLabel xml:lang='de'>BAR</skos:prefLabel>
</root>"""

root = etree.fromstring(doc)
nsmap = root.nsmap
nsmap["xml"] = "http://www.w3.org/XML/1998/namespace" 

en = root.find(".//skos:prefLabel[@xml:lang='en']", namespaces=nsmap)
print(en.text)

Output:

FOO