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

感情迁移 提交于 2019-11-27 03:26:05

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!