Setting and accessing namespaces in python lxml
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Mysterious Puzzle
--
Chapters
00:00 Question
01:58 Accepted answer (Score 1)
02:32 Thank you
--
Full question
https://stackoverflow.com/questions/4811...
Accepted answer links:
[root.nsmap]: http://lxml.de/api/lxml.etree._Element-c...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #namespaces #lxml
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Mysterious Puzzle
--
Chapters
00:00 Question
01:58 Accepted answer (Score 1)
02:32 Thank you
--
Full question
https://stackoverflow.com/questions/4811...
Accepted answer links:
[root.nsmap]: http://lxml.de/api/lxml.etree._Element-c...
--
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