Home > front end >  append new nodes and attributes in xml file using xmlstarlet
append new nodes and attributes in xml file using xmlstarlet

Time:01-21

I have xml file format like this

<project>
  <node name="abc" description="abc-describe" tags="test-tag"
        osFamily="unix" osName="Ubuntu">
  </node>
  <node name="def" description="def-describe" tags="test-tag"
        osFamily="unix" osName="Ubuntu">
  </node>
 
</project>

now after appending new node name it should look like this

<project>
  <node name="abc" description="abc-describe" tags="test-tag"
        osFamily="unix" osName="Ubuntu">
  </node>
  <node name="def" description="def-describe" tags="test-tag"
        osFamily="unix" osName="Ubuntu">
  </node>
  <node name="xyz" description="xyz-describe" tags="test-tag"
        osFamily="unix" osName="Ubuntu">
  </node>
 
</project>

but when I append using xml commands it is adding as shown in below format. Its not closing the subnode.

    <project>
  <node name="abc" description="abc-describe" tags="test-tag"
        osFamily="unix" osName="Ubuntu">
  </node>
  <node name="def" description="def-describe" tags="test-tag"
        osFamily="unix" osName="Ubuntu">
  </node>
  <node name="xyz" description="xyz-describe" tags="test-tag"
        osFamily="unix" osName="Ubuntu" />
   
</project>

here is the command which i used.

xmlstarlet ed -L -s "/project" -t elem -n node -i "//node[3]"  -t attr -n "name" -v "xyz" -i  "//node[3]" -t attr -n "description" -v "xyz-describe" -i  "//node[3]" -t attr -n "tags" -v "test-tag" -i "//node[3]" -t attr -n "osFamily" -v "unix" -i  "//node[3]" -t attr -n "osName" -v "Ubuntu" file.xml

can someone help me on this?

CodePudding user response:

You could add an empty text node (or one containing a newline and indentation):

xmlstarlet edit \
  -s '/project' -t elem -n node \
  --var nd '$prev' \
  -s '$nd' -t text -n 'ignored' -v '' \
  -s '$nd' -t attr -n 'name' -v 'xyz' \
  … \
file.xml
  • --var defines a named variable, and the $prev variable refers to the node(s) created by the most recent -s, -i, or -a option which all define or redefine it (see xmlstarlet.txt for examples of --var and $prev)
  • is where the remaining attributes belong
  • Related