Home > Software design >  How to replace xml tag value using xmlstarlet command?
How to replace xml tag value using xmlstarlet command?

Time:12-07

I'm trying to change a tag value in xml using sed command. I also used xmlstarlet as well but didn't help because of CDATA tag. Below is the tag.

xmlstarlet changes <> to &gt; and &lt; respectively.

xmlstarlet ed -u '//item[@name]/val' -v '<![CDATA[1234]]>' file.xml

output:

  <item name="Rx_Frequency">
    <val>&lt;\![CDATA[1234]]&gt;</val>
  </item>

sample input

<item name="Rx_Frequency">
    <val><![CDATA[xxx]]></val>
</item>

expected output:

<item name="Rx_Frequency">
    <val><![CDATA[1234]]></val>
</item>

CodePudding user response:

xmllintcan be used too

printf '%s\n' 'cd //item[@name]/val' 'set <![CDATA[1234]]>' 'save' 'bye' | xmllint --shell tmp.xml

Command output

/ > cd //item[@name]/val
val > set <![CDATA[1234]]>
val > save
val > bye

Result

<item name="Rx_Frequency">
    <val><![CDATA[1234]]></val>
</item>

CodePudding user response:

With xmlstarlet. I assume your file does not use namespaces.

xmlstarlet edit --omit-decl \
  --update '//item[@name]/val' --value '<![CDATA[1234]]>' file.xml | xmlstarlet unescape

Output:

<item name="Rx_Frequency">
  <val><![CDATA[1234]]></val>
</item>

See: xmlstarlet unescape --help

  • Related