可能的重复:
使用lxml时,可以在没有命名空间属性的情况下呈现XML吗? https://stackoverflow.com/questions/5084730/when-using-lxml-can-the-xml-be-rendered-without-namespace-attributes
如何从 python 中剥离 python 属性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>
我希望输出看起来像:
<foo>
<bar>hi</bar>
<baz>1</baz>
<fritz/>
</foo>
您可以通过使用来完成此操作etree.strip_attributes http://lxml.de/api/lxml.etree-module.html#strip_attributes and etree.cleanup_namespaces http://lxml.de/api/lxml.etree-module.html#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>
这仍然留下了xsi:nil
参考,您可以类似地删除它。
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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)