让lxml不要创建自关闭标签

Lau*_*RTE 4 python lxml

我有一个(旧的)工具,不懂自我关闭标签<STATUS/>.因此,我们需要使用打开/关闭标记序列化我们的XML文件,如下所示:<STATUS></STATUS>.

目前我有:

>>> from lxml import etree

>>> para = """<ERROR>The status is <STATUS></STATUS>.</ERROR>"""
>>> tree = etree.XML(para)
>>> etree.tostring(tree)
'<ERROR>The status is <STATUS/>.</ERROR>'
Run Code Online (Sandbox Code Playgroud)

如何使用打开/关闭的标签进行序列化?

<ERROR>The status is <STATUS></STATUS>.</ERROR>
Run Code Online (Sandbox Code Playgroud)

wildwilhelm给出,如下:

>>> from lxml import etree

>>> para = """<ERROR>The status is <STATUS></STATUS>.</ERROR>"""
>>> tree = etree.XML(para)
>>> for status_elem in tree.xpath("//STATUS[string() = '']"):
...     status_elem.text = ""
>>> etree.tostring(tree)
'<ERROR>The status is <STATUS></STATUS>.</ERROR>'
Run Code Online (Sandbox Code Playgroud)

Bob*_* Du 8

如果你 tostring lxml dom 是HTML,你可以使用

etree.tostring(html_dom, method='html')
Run Code Online (Sandbox Code Playgroud)

防止像这样的自闭标签<a />


wil*_*elm 5

似乎<STATUS>标签被赋予了以下text属性None:

>>> tree[0]
<Element STATUS at 0x11708d4d0>
>>> tree[0].text
>>> tree[0].text is None
True
Run Code Online (Sandbox Code Playgroud)

如果text<STATUS>标记的属性设置为空字符串,则应该得到您要查找的内容:

>>> tree[0].text = ''
>>> etree.tostring(tree)
'<ERROR>The status is <STATUS></STATUS>.</ERROR>'
Run Code Online (Sandbox Code Playgroud)

考虑到这一点,您可以text在写出XML之前使用DOM树并修复属性.像这样的东西:

# prevent creation of self-closing tags
for node in tree.iter():
    if node.text is None:
        node.text = ''
Run Code Online (Sandbox Code Playgroud)