opeanut
opeanut

Reputation: 11

Suppress automatically added namespace in etree Python

<rootTag xmlns="model">
<tag>

I have an xml file with a namespace specified as above. I can use etree in Python to parse it, but after making changes and writing it back to the file, etree changes it to this

<rootTag xmlns:ns0="model">
<ns0:tag>

and prepended "ns0" to all the tags. I don't want that to happen. A sample program is as follows:

et = xml.etree.ElementTree.parse(xml_name)
root = (et.getroot())
root.find('.//*'+pattern).text = new_text
et.write(xml_name)

Is there someway to suppress this automatic change? Thanks

Upvotes: 1

Views: 724

Answers (1)

Daniel Haley
Daniel Haley

Reputation: 52858

This can be done using register_namespace() by using an empty string for the prefix...

ET.register_namespace("", "model")

Full working example...

import xml.etree.ElementTree as ET

xml = """
<rootTag xmlns="model">
    <tag>foo</tag>
</rootTag>
"""

ET.register_namespace("", "model")

root = ET.fromstring(xml)
root.find("{model}tag").text = "bar"
print(ET.tostring(root).decode())

printed output...

<rootTag xmlns="model">
    <tag>bar</tag>
</rootTag>

Also see this answer for another example.

Upvotes: 2

Related Questions