9

I am generating some XML with lxml and getting nodes generated like this:

<QBXML 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">

and:

<MaxReturned py:pytype="int">

These custom attributes are killing Quickbooks' parser. Can I get LXML to render without the custom stuff?

Randy Syring
  • 1,971
  • 1
  • 15
  • 19

3 Answers3

13

Looks like the following take care of it:

objectify.deannotate(root, xsi_nil=True)
etree.cleanup_namespaces(root)

or, if using lxml >= 2.3.2 (thanks @Pedru):

objectify.deannotate(root, cleanup_namespaces=True, xsi_nil=True)
Randy Syring
  • 1,971
  • 1
  • 15
  • 19
  • 1
    from lxml version 2.3.2 you can pass `cleanup_namespaces=True` to `objectify.deannotate()` (no need to call `etree.cleanup_namespaces()`) – Pedru Mar 24 '16 at 10:55
0

If you want to have nested XML you can do this:

from lxml import objectify
doc = objectify.ElementMaker(annotate=False)
doc = (objectify.E.configuration(getattr(objectify.E,'networklists'),name="acl.conf",description="Network Lists"))
objectify.deannotate(doc,cleanup_namespaces=True)

The output with custom attributes is like this:

<configuration description="Network Lists" name="acl.conf">
<network-lists>

</network-lists>
</configuration>
Soraya Anvari
  • 179
  • 2
  • 5
-2

if you're using

etree.fromstring(xml_response)

then doing this:

xml_response.replace(' xmlns:', ' xmlnamespace:').replace(' xmlns=', ' xmlnamespace=')

avoids it ever parsing namespaces

BenH
  • 894
  • 8
  • 7