我有几个 xml 文件。它们都具有相同的结构,但由于文件大小而被拆分。所以,假设我有 A.xml
、B.xml
、C.xml
和 D.xml
以及想要使用命令行工具将它们组合/合并到 combined.xml
。
A.xml
<products>
<product id="1234"></product>
...
</products>
B.xml
<products>
<product id="5678"></product>
...
</products>
等等
最佳答案
高科技回答:
将此 Python 脚本保存为 xmlcombine.py
:
#!/usr/bin/env python
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__":
run(sys.argv[1:])
要合并文件,运行:
python xmlcombine.py ?.xml > combined.xml
要进一步增强,请考虑使用:
chmod +x xmlcombine.py
: 允许您在命令行中省略python
xmlcombine.py !(combined).xml > combined.xml
: 收集除输出之外的所有 XML 文件,但需要 bash 的extglob
选项xmlcombine.py *.xml |海绵组合.xml
: 也收集combined.xml
中的所有内容,但需要sponge
程序将 lxml.etree 导入为 ElementTree
: 使用可能更快的 XML 解析器
关于xml - 从命令行合并多个 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9004135/