Keep lxml from creating self-closing tags

前端 未结 2 1484
遥遥无期
遥遥无期 2020-12-20 20:37

I have a (old) tool which does not understand self-closing tags like . So, we need to serialize our XML files with opened/closed tags like this:

2条回答
  •  执笔经年
    2020-12-20 21:17

    It seems like the tag gets assigned a text attribute of None:

    >>> tree[0]
    
    >>> tree[0].text
    >>> tree[0].text is None
    True
    

    If you set the text attribute of the tag to an empty string, you should get what you're looking for:

    >>> tree[0].text = ''
    >>> etree.tostring(tree)
    'The status is .'
    

    With this is mind, you can probably walk a DOM tree and fix up text attributes before writing out your XML. Something like this:

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

提交回复
热议问题