python - 从 lxml.objectify.ObjectifiedElement 中剥离 p

这个问题在这里已经有了答案:
关闭10年前.

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/

相关文章:

javascript - 谷歌图表显示金钱而​​不是百分比

formatting - 是否可以使 PHP 错误看起来更好? Stack 可以在单独的行上跟踪输出

c# - 将规范化的电话号码转换为用户友好的版本

c++ - 在不改变缩进的情况下重新格式化 C++ 大括号?

eclipse - 在 Eclipse 格式化程序中的花括号上强制 "same line"

c# - 格式异常 - 日期时间和小时

python - 在 Python 中将浮点列表转换为字符串

javascript - 有没有办法使用 Moment.js 解析相对日期?

django - 如何格式化 django 评论的表单字段?

.net - 如何将 NLog 的文件名设置为进程开始日期?