Search code examples
bashxmlstarlet

Updating XML file using xmlstartlet


I have the following XML structure

<config>
   <keys>
     <add key="Name" value="myApp" />
     <add key="BuildVersion" value="1" />
     ...
   </keys>
</config>

I would like to match on the element corresponding to key "BuildVersion" and update its value to "2". This is what I went with,

xmlstarlet ed -u "//config/keys/add[@key='BuildVersion']" -v '2' App.xml

But it resulted in the following output

<add key="BuildVersion" value="1">2</app>

I would instead like the below output

<add key="BuildVersion" value="2" />

Solution

  • Just add /@value to your XPath expression, like this:

    xmlstarlet ed -u "//config/keys/add[@key='BuildVersion']/@value" --value "2" App.xml
    

    The above prints:

    <?xml version="1.0"?>
    <config>
      <keys>
        <add key="Name" value="myApp"/>
        <add key="BuildVersion" value="2"/>
      </keys>
    </config>