Possible Duplicate:
When using lxml, can the XML be rendered without namespace attributes?
如何从 lxml.objectify.ObjectifiedElement
中去除 python 属性?
示例:
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
来完成此操作和 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>
这仍然留下 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>
关于python - 从 lxml.objectify.ObjectifiedElement 中剥离 python 命名空间属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6141464/