4

I have been trying to to add new elements to an XML file.

Original file:

<levela>
  <levelb>
  </levelb>
</levela>

I'm trying to get the following result:

<levela>
  <levelb>
    <levelc>
      <element1>value1</element1>
      <element2>value2</element2>
      <element3>value3</element3>
    </levelc>
  </levelb>
</levela>

My current attempt is:

xmlstarlet ed -a /levela/lelvelb -t elem -n levelc -v "" \
    -i //levelc -t elem -n "element1" -v "value1" \
    file.xml

But my file isn't updated.

1 Answer 1

3

There’s a typo in your xmlstarlet invocation (lelvelb):

xmlstarlet ed -a /levela/lelvelb -t elem -n levelc -v "" \
    -i //levelc -t elem -n "element1" -v "value1" \
    file.xml

To add a subnode, you need to use the -s operation, not -a or -i:

xmlstarlet ed -s /levela/levelb -t elem -n levelc -v "" \
    -s //levelc -t elem -n "element1" -v "value1" \
    file.xml

This produces

<?xml version="1.0"?>
<levela>
  <levelb>
  <levelc><element1>value1</element1><element2>value2</element2></levelc></levelb>
</levela>

You can add other -s operations as necessary. You can also drop the empty -v for levelc.

If you want to modify file.xml itself, instead of getting the result of the transformation on xmlstarlet’s standard output, add the -L option to ed:

xmlstarlet ed -L -s /levela/levelb -t elem -n levelc -v "" \
    -s //levelc -t elem -n "element1" -v "value1" \
    file.xml
2
  • Ah yes, thanks @muru! Commented Jun 7, 2019 at 7:43
  • This is a brilliant question and answer. Thank you. Commented Nov 27, 2019 at 4:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .