问题
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?
回答1:
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)
回答2:
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>
回答3:
if you're using
etree.fromstring(xml_response)
then doing this:
xml_response.replace(' xmlns:', ' xmlnamespace:').replace(' xmlns=', ' xmlnamespace=')
avoids it ever parsing namespaces
来源:https://stackoverflow.com/questions/5084730/when-using-lxml-can-the-xml-be-rendered-without-namespace-attributes