xmlstarlet update an attribute

renard picture renard · Oct 20, 2011 · Viewed 8.5k times · Source

I'm working on a script which deals with an xml file. I'd like to update an attribute value in this xml file with xmlstarlet but it doesn't work.

Here is a sample of the xml file:

<?xml version="1.0" encoding="UTF-8"?>
<channel name="xfce4-keyboard-shortcuts" version="1.0">
  <property name="commands" type="empty">
    <property name="default" type="empty">
      <property name="&lt;Alt&gt;F2" type="empty"/>
      <property name="&lt;Control&gt;&lt;Alt&gt;Delete" type="empty"/>
      <property name="XF86Display" type="string" value="xrandr --output LVDS --auto --output VGA-0 --mode 1680x1050_60.00 --right-of LVDS"/>
    </property>
    <property name="custom" type="empty">
      <property name="&lt;Alt&gt;F2" type="string" value="xfrun4"/>
      <property name="&lt;Control&gt;&lt;Alt&gt;Delete" type="string" value="xflock4"/>
      <property name="XF86Display" type="string" value="xrandr --output LVDS --auto --output VGA-0 --mode 1680x1050_60.00 --right-of LVDS"/>
      <property name="override" type="bool" value="true"/>
    </property>
  </property>
</channel>

And here is the command to update the property with the name "XF86Display" in the custom property node.

xmlstarlet edit \
  --update "/xml/channel[@name=xfce4-keyboard-shortcuts]/property[@name=commands]/property[@name=custom]/property[@name=XF86Display]/@value" \
  --value "test" xfce4-keyboard-shortcuts.xml

This output is strictly the same to the input...

Thank you

Answer

mzjn picture mzjn · Oct 20, 2011

This works for me (the root is <channel>; attribute values quoted):

xmlstarlet edit \
  --update "/channel[@name='xfce4-keyboard-shortcuts']/property[@name='commands']/property[@name='custom']/property[@name='XF86Display']/@value" \
  --value  "test" xfce4-keyboard-shortcuts.xml

Or simpler:

xmlstarlet edit \
  --update "//property[@name='XF86Display']/@value" \
  --value "test" xfce4-keyboard-shortcuts.xml