Search code examples
xmlshellxmlstarlet

How to add text to an xml structure using xmlstarlet


I'm trying to add a text field to a xml structure using xmlstarlet, but can't get it to work. This is the closest I got.

xmlstarlet edit --append "//foo/bar[@baz='qux']" -t text -n grault -v "garply" <<EOF
<foo>
   <bar baz="qux">
     <quux quuz="corge"/>
   </bar>
</foo>
EOF

This results in :

<?xml version="1.0"?>
<foo>
  <bar baz="qux">
    <quux quuz="corge"/>
  </bar>garply
</foo>

While I expected this:

<?xml version="1.0"?>
<foo>
  <bar baz="qux">
    <quux quuz="corge"/>
    <grault>garply</grault>
  </bar>
</foo>

Can someone enlighten me about the errors of my ways?

Thanks in advance.


Solution

  • I assume you need a subnode:

    xmlstarlet edit --subnode "//foo/bar" -t elem -n "grault" -v "garply" file.xml
    

    Output:

    <?xml version="1.0"?>
    <foo>
      <bar baz="qux">
        <quux quuz="corge"/>
        <grault>garply</grault>
      </bar>
    </foo>
    

    See: xmlstarlet edit