簡體   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