newkid101 newkid101 -4 years ago 145
Bash Question

Bash insert subnode to XML file

Im trying to edit a config file using bash. My file looks like this:

<configuration>
<property>
<name></name>
<value></value>
</property>
<property>
<name></name>
<value></value>
</property>
</configuration>


I want to add another couple of
<property>
blocks to the file. Since all
property
tags are enclosed inside the
configuration
tags the file would looks like this:

<configuration>
<property>
<name></name>
<value></value>
</property>
<property>
<name></name>
<value></value>
</property>
<property>
<name></name>
<value></value>
</property>
</configuration>


I came across this post and followed the accepted answer, however nothing is appended to my file and the xml block I try to append is "echo-ed" as a single line string.
My bash file looks like this:

file=/path/to/file/oozie-site.xml
content="<property>\n<name></name>\n<value></value>\n</property>\n<property>\n<name></name>\n<value></value>\n</property>"
echo $content
C=$(echo $content | sed 's/\//\\\//g')
sed "/<\/configuration>/ s/.*/${C}\n&/" $file

Answer Source

With xmlstarlet:

xmlstarlet ed --omit-decl \
  -s '//configuration' -t elem -n "property" \
  -s '//configuration/property[last()]' -t elem -n "name" \
  -s '//configuration/property[last()]' -t elem -n "value" \
  file.xml

Output:

<configuration>
  <property>
    <name/>
    <value/>
  </property>
  <property>
    <name/>
    <value/>
  </property>
  <property>
    <name/>
    <value/>
  </property>
</configuration>

--omit-decl: omit XML declaration

-s: add a subnode (see xmlstarlet ed for details)

-t elem: set node type, here: element

-n: set name of element

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download