Home > Mobile >  xmlstarlet: How to insert nested element?
xmlstarlet: How to insert nested element?

Time:11-17

Im trying to add one <Product> element with nested -> to the <Products> list.

From this XML:

<Products>
  <Product>
    <Name>
      product1
    </Name>
  </Product>
</Products>

Want to finish like this:

<Products>
  <Product>
    <Name>
      product1
    </Name>
  </Product>
  <Product>
    <Name>
      product2
    </Name>
  </Product>
</Products>

this is my snippet attemp:

xmlstarlet ed --inplace -s /Products -t elem -n "Product" -v "" \
-s //Product -t elem -n "name" -v "product2" \
Settings.xml

the problem is that every current <Product> is get 1 more <Name> element:

  <Products>
    <Product>
      <name>
        product1
      </name>
      <name>
        product2
      </name>
    </Product>
    <Product>
      <name>
        product2
      </name>
    </Product>
  <Products>

CodePudding user response:

Try it this way

xmlstarlet ed --subnode "//Products" --type elem -n Product \
--subnode "//Products/Product[last()]" --type elem -n \n
"Name"  --value "product2" Settings.xml

and see if it works.

  • Related