从命令行合并多个XML文件

Tut*_*mon 14 xml merge command-line

我有几个xml文件.它们都具有相同的结构,但由于文件大小而被拆分.所以,让我们说我有A.xml,B.xml,C.xmlD.xml和要合并/它们合并到combined.xml,使用命令行工具.

A.XML

<products>
    <product id="1234"></product>
    ...
</products>
Run Code Online (Sandbox Code Playgroud)

B.XML

<products>
  <product id="5678"></product>
  ...
</products>
Run Code Online (Sandbox Code Playgroud)

等等

esw*_*ald 16

高科技答案:

将此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:])
Run Code Online (Sandbox Code Playgroud)

要合并文件,请运行:

python xmlcombine.py ?.xml > combined.xml
Run Code Online (Sandbox Code Playgroud)

要进一步增强,请考虑使用:

  • chmod +x xmlcombine.py:允许您python在命令行中省略

  • xmlcombine.py !(combined).xml > combined.xml:收集除输出之外的所有XML文件,但需要bash的extglob选项

  • xmlcombine.py *.xml | sponge combined.xml:收集所有内容combined.xml,但需要该sponge程序

  • import lxml.etree as ElementTree:使用可能更快的XML解析器


ber*_*erk 9

xml_grep

http://search.cpan.org/dist/XML-Twig/tools/xml_grep/xml_grep

xml_grep --pretty_print indented --wrap products --descr'' - second"product"*.xml> combined.xml

  • --wrap:使用给定标记封装/包装xml结果.(这里products)
  • --cond:将XML子树到grep(这里product)