«

»

Feb 02

Setting xml:lang with lxml

Unlike every other attribute I’ve run across, setting xml:lang kept failing with an ‘invalid attribute name’ error. After the jump is how I fixed it.

Python and lxml make things easy. Really easy. So I was a bit lost in the woods when it kept throwing an ‘invalid attribute name’ error when I would try to set the xml:lang attribute. After a bit of digging, I found This post on Ditanauts.org.

Turns out setting xml:lang is a little special. Where I begin to write the xml out looks like this:

topline = ET.Element('cXML')
topline.set("timestamp", timestamp) # set topline tags
topline.set("payloadID", payload)

Now where I was trying the same, eg topline.set("xml:lang", "en-US"), that wasn’t happening. Instead I had to do this, as Ditanauts makes clear:
attr = topline.attrib
attr['{http://www.w3.org/XML/1998/namespace}lang'] = "en-US"

Works like a charm.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>