Stripping python namespace attributes from an lxml.objectify.ObjectifiedElement

Daenyth picture Daenyth · May 26, 2011 · Viewed 7.2k times · Source

Possible Duplicate:
When using lxml, can the XML be rendered without namespace attributes?

How can I strip the python attributes from an lxml.objectify.ObjectifiedElement?

Example:

In [1]: from lxml import etree, objectify
In [2]: foo = objectify.Element("foo")
In [3]: foo.bar = "hi"
In [4]: foo.baz = 1
In [5]: foo.fritz = None
In [6]: print etree.tostring(foo, pretty_print=True)
<foo xmlns:py="http://codespeak.net/lxml/objectify/pytype" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" py:pytype="TREE">
  <bar py:pytype="str">hi</bar>
  <baz py:pytype="int">1</baz>
  <fritz xsi:nil="true"/>
</foo>

I'd instead like the output to look like:

<foo>
  <bar>hi</bar>
  <baz>1</baz>
  <fritz/>
</foo>

Answer

Daenyth picture Daenyth · May 26, 2011

You can accomplish this by using etree.strip_attributes and etree.cleanup_namespaces.

In [8]: etree.strip_attributes(foo, '{http://codespeak.net/lxml/objectify/pytype}pytype')
In [9]: print etree.tostring(foo, pretty_print=True)
<foo xmlns:py="http://codespeak.net/lxml/objectify/pytype" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <bar>hi</bar>
  <baz>1</baz>
  <fritz xsi:nil="true"/>
</foo>

In [10]: etree.cleanup_namespaces(foo)
In [11]: print etree.tostring(foo, pretty_print=True)
<foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <bar>hi</bar>
  <baz>1</baz>
  <fritz xsi:nil="true"/>
</foo>

This still leaves the xsi:nil reference, which you can strip similarly.

In [12]: etree.strip_attributes(foo, '{http://www.w3.org/2001/XMLSchema-instance}nil')
In [13]: etree.cleanup_namespaces(foo)
In [14]: print etree.tostring(foo, pretty_print=True)
<foo>
  <bar>hi</bar>
  <baz>1</baz>
  <fritz/>
</foo>