python - 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 中观察到。
解决方案
如此处所述,默认编码ElementTree.tostring()
为US-ASCII
. 将encoding
参数设置为unicode
。这将相应地解析\n
。
ElementTree.tostring(first, encoding="unicode"))
推荐阅读
- c# - 我想在侧面导航栏 blazor C# 中分层显示类别
- c++ - 如何防止 CreateProcess/ShellExecute 重置 Windows 空闲计时器?
- powershell - Powershell在forloop中访问具有多个属性的XML节点
- while-loop - 而真:尝试:除了ValueError:
- reactjs - 反应复选框未在功能组件中更新
- akka - Akka 远程性能问题
- python - 是否可以用我们自己的数据训练 gpt2 来生成文本?
- android - 关闭 AlertDialog 后 Edittext 获得焦点并显示键盘
- hbase - 如何只更新凤凰中的一列?
- javascript - 生成 9 张随机图像并将其放入滑块/轮播中