繁体   English   中英

如何使用xmlstarlet合并两个xml文件

[英]How to merge two xml files using xmlstarlet

我有两个示例xml文件,我想合并其中的元素。

如果我运行xmlstarlet sel -t -c "//data" input1.xml input2.xml ,我有两次data标签(我知道这是正确的结果),但是我只希望合并该item标签,只有一个标签。

这是我的输入文件

input1.xml:

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<demo:pub xsi:schemaLocation="demo_1_0 demo.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:demo="demo_1_0">
  <data>
    <item>
      <fieldA>12</fieldA>
      <fieldB>Hello world</fieldB>
    </item>
    <item>
      <fieldA>15</fieldA>
      <fieldB>The book is yellow</fieldB>
    </item>
  </data>
</demo:pub>

input2.xml:

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<demo:pub xsi:schemaLocation="demo_1_0 demo.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:demo="demo_1_0">
  <data>
    <item>
      <fieldA>08</fieldA>
      <fieldB>Hello world II</fieldB>
    </item>
    <item>
      <fieldA>06</fieldA>
      <fieldB>The book is orange</fieldB>
    </item>
  </data>
</demo:pub>

我想有这样的事情:

<data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:demo="demo_1_0">
    <item>
      <fieldA>12</fieldA>
      <fieldB>Hello world</fieldB>
    </item>
    <item>
      <fieldA>15</fieldA>
      <fieldB>The book is yellow</fieldB>
    </item>
    <item>
      <fieldA>08</fieldA>
      <fieldB>Hello world II</fieldB>
    </item>
    <item>
      <fieldA>06</fieldA>
      <fieldB>The book is orange</fieldB>
    </item>
</data>

将两个XML文件与xmlstarlet和bash结合使用:

echo "<data/>" | xmlstarlet edit \
  --insert '//data' --type attr -n 'xmlns:xsi' --value 'http://www.w3.org/2001/XMLSchema-instance' \
  --insert '//data' --type attr -n 'xmlns:demo' --value 'demo_1_0' \
  --subnode '//data' --type text -n '' --value "$(xmlstarlet select --omit-decl -t --copy-of '//data/item' input1.xml)" \
  --subnode '//data' --type text -n '' --value "$(xmlstarlet select --omit-decl -t --copy-of '//data/item' input2.xml)" \
  | xmlstarlet unescape \
  | xmlstarlet format --omit-decl --nsclean

输出:

<data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:demo="demo_1_0">
  <item>
    <fieldA>12</fieldA>
    <fieldB>Hello world</fieldB>
  </item>
  <item>
    <fieldA>15</fieldA>
    <fieldB>The book is yellow</fieldB>
  </item>
  <item>
    <fieldA>08</fieldA>
    <fieldB>Hello world II</fieldB>
  </item>
  <item>
    <fieldA>06</fieldA>
    <fieldB>The book is orange</fieldB>
  </item>
</data>

请参阅: xmlstarlet --helpxmlstarlet edit --helpxmlstarlet format --help

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM