首页 > 解决方案 > Python 3:合并两个 xml 时 print() 不处理 '\n'

问题描述

合并.py:

import sys
from xml.etree import ElementTree

def run(files):
    first = None
    for filename in files:
        data = ElementTree.parse(filename).getroot()
        if first is None:
            first = data
        else:
            first.extend(data)
    if first is not None:
        print (ElementTree.tostring(first))
    
if __name__ == "__main__":
    files = None
    if len(sys.argv[1:]) != 0:
        files = "".join(sys.argv[1:]).split('\n')
        run(files)
    else:
        raise Exception("Sorry, no files found")

在运行上述将 xmls 文件合并为一个的代码时,输​​出如下所示,提供的最小输出:

预期输出:

<a>
<b> ---ABCD
-----</b>

实际输出:

<a><b> ---ABCD\n----</b>

它是如何被调用的:

python3 merge.py `find "path/" -type f -name *.xml"` > "path/combined.xml"

PS:它适用于 Python。仅在 Python3 中观察到。

标签: pythonpython-3.xxmlmergeelementtree

解决方案


如此所述,默认编码ElementTree.tostring()US-ASCII. 将encoding参数设置为unicode。这将相应地解析\n

ElementTree.tostring(first, encoding="unicode"))

推荐阅读