Serializing non-qualified attributes with ElementTree

Posted on Mon 21 November 2011 in Coding

The other day, I had a piece of Python code that deserialized an XML text containing a UPnP service description to an ElementTree instance using ElementTree.parse, then at a later stage serialized it back to XML using ElementTree.write.

Now, the service description happened to contain non-qualified attributes (like this: <stateVariable sendEvents="no">), which caused the serialization to raise an error with the message “cannot use non-qualified names with default_namespace option.” Googling around a bit didn’t help much, since not many seem to have had this problem, or there is no good solution to be found. (A few days later, this XKCD strip was published. Spot on!)

So, inspired by example code at, I wrote the following workaround that simple updates each non-qualified attribute with the namespace of its parent element during parsing. This is most definitively not a proper solution, but it works in my case. Perhaps it’ll help somebody else too!