python - 序列化为字符串时,如何防止 lxml 自动关闭空元素?

标签 python lxml

我正在解析一个巨大的 xml 文件,其中包含许多空元素,例如

<MemoryEnv></MemoryEnv>

序列化时

etree.tostring(root_element, pretty_print=True)

输出元素折叠为

<MemoryEnv/>

有什么办法可以避免这种情况吗? etree.tostring() 不提供这样的功能。

有没有办法干扰 lxml 的 tostring() 序列化程序?

顺便说一句,html 模块不起作用。它不是为 XML 设计的,并且 它不会以原始形式创建空元素。

问题是,尽管空元素的折叠和未折叠形式是等价的, 解析此文件的程序将无法处理折叠的空元素。

最佳答案

这里有一个方法可以做到这一点。确保所有空元素的 text 值不是 None

例子:

from lxml import etree

XML = """
<root>
  <MemoryEnv></MemoryEnv>
  <AlsoEmpty></AlsoEmpty>
  <foo>bar</foo>
</root>"""

doc = etree.fromstring(XML)

for elem in doc.iter():
    if elem.text == None:
        elem.text = ''

print etree.tostring(doc)

输出:

<root>
  <MemoryEnv></MemoryEnv>
  <AlsoEmpty></AlsoEmpty>
  <foo>bar</foo>
</root>

另一种方法是使用 write_c14n()写法canonical XML (不使用特殊的空元素语法)到文件。

from lxml import etree

XML = """
<root>
  <MemoryEnv></MemoryEnv>
  <AlsoEmpty></AlsoEmpty>
  <foo>bar</foo>
</root>"""

doc = etree.fromstring(XML)

doc.getroottree().write_c14n("out.xml")

关于python - 序列化为字符串时,如何防止 lxml 自动关闭空元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34111154/

相关文章:

python - 有谁知道如何在python中绘制线性回归曲线或相关函数来绘制它?

python - 获取源代码行 lxml python 中的所有元素

python - LXML 是否有可能检测到一个类在 HTML 中具有什么值?

python - 创建时向 lxml.etree.Element 添加尾部

python - xmlns 命名空间破坏 lxml

python - 字符串转义字符

python - Django : Fetch XML, 中的 urllib2/pycurl 检查 HTTP 状态,检查 HTTPS 连接

python - 在Python中,对象有自己的类变量副本吗?

python - 抑制织物运行输出的简单方法?

python - 在解析之前使用 lxml 注册命名空间