LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   How to search for a corresponding tag in xml file and replace the corresponding value (https://www.linuxquestions.org/questions/linux-newbie-8/how-to-search-for-a-corresponding-tag-in-xml-file-and-replace-the-corresponding-value-4175427688/)

userofunix 09-17-2012 03:03 PM

How to search for a corresponding tag in xml file and replace the corresponding value
 
Hello Everyone,

I've to modify hundreds of xml files by looking for a one or more specific tags and then change the corresponding value for the ones matching. Is it possible to do using a quick shell script.

Let's say, I've an xml file like below and the matching tags file contain 'abcd' and 'efgh', then I want to toggle the 'ignore' arg for those two only to true.

i/p

<?xml version="1.0" encoding="UTF-8"?>
<test-case id="">
<import name="abcd" id="id1" module-dir="loc1">
<arg name="arg1" value="${val1}"/>
<arg name="arg2" value="${val2}"/>
<arg name="ignore" value="false"/>
</import>
<import name="xyz" id="id2" module-dir="loc1">
<arg name="arg1" value="${val1}"/>
<arg name="arg2" value="${val2}"/>
<arg name="ignore" value="false"/>
</import>
<import name="efgh" id="id3" module-dir="loc2">
<arg name="arg1" value="${val1}"/>
<arg name="arg2" value="${val2}"/>
<arg name="ignore" value="false"/>
</import>
...
</test-case>

after running the script, I want the file to look like:

<?xml version="1.0" encoding="UTF-8"?>
<test-case id="">
<import name="abcd" id="id1" module-dir="loc1">
<arg name="arg1" value="${val1}"/>
<arg name="arg2" value="${val2}"/>
<arg name="ignore" value="true"/>
</import>
<import name="xyz" id="id2" module-dir="loc1">
<arg name="arg1" value="${val1}"/>
<arg name="arg2" value="${val2}"/>
<arg name="ignore" value="false"/>
</import>
<import name="efgh" id="id3" module-dir="loc2">
<arg name="arg1" value="${val1}"/>
<arg name="arg2" value="${val2}"/>
<arg name="ignore" value="true"/>
</import>
...
</test-case>

ntubski 09-17-2012 03:42 PM

Using XMLStarlet:

Code:

find path/to/xml/files/ -name '*.xml' -print0 | \
 xargs -0 xmlstarlet ed -L -P \
  -u '/test-case/import[@name = "abcd" or @name = "efgh"]/arg[@name = "ignore"]/@value' \
  -x 'not(. = "true")'

Quote:

then I want to toggle the 'ignore' arg for those two only to true.
The above code toggles, if you meant just set to true always then the last line should be
Code:

-v true


All times are GMT -5. The time now is 09:41 PM.