Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing tag data in an XML file using windows batch file

I have an XML file with several tags in it, and I am trying to change the contents of one of these tags with a batch script.

An example of the xml file is:

<ConfigurationData>
<ReportsFolder>\Reports</ReportsFolder>
<Helpfolder>\Help</HelpFolder>
<InstallationType>Terminal</InstallationType>
<LicenseFolder>..\License</LicenseFolder>
</ConfigurationData>

I am trying to change the data between <InstallationType> and </InstallationType> to another variable of my choosing. I'm thinking I would need some sort of For loop to find that part of the xml file, but I'm lost as to how I would edit just that one section.

like image 265
user2382144 Avatar asked Jun 11 '13 21:06

user2382144


2 Answers

You really should use a tool that is designed specifically to manipulate XML.

But in a pinch, you could use any tool that can do a regex search and replace to do a naive solution that would work with the file as you have it laid out, but might fail with a logically equivalent XML file that has had the physical layout rearranged.

I like to use a hybrid JScript/batch utility I wrote called REPL.BAT to manipulate text files via batch scripts. The script will run on any native Windows machine from XP onward, and it does not require installation of any 3rd party executables. Click the link to get the script code and a more thorough description.

Using REPL.BAT, a fast and efficient but naive solution is as simple as:

setlocal enableDelayedExpansion
set "newValue=myNewValue"
type "fileName.xml"|repl "(<InstallationType>).*(</InstallationType>)" "$1!newValue!$2" >fileName.xml.new
move /y "fileName.xml.new" "fileName.xml"
like image 100
dbenham Avatar answered Oct 13 '22 11:10

dbenham


@echo off
setlocal EnableDelayedExpansion

set anotherVariable=New value

(for /F "delims=" %%a in (theFile.xml) do (
   set "line=%%a"
   set "newLine=!line:InstallationType>=!"
   if "!newLine!" neq "!line!" (
      set "newLine=<InstallationType>%anotherVariable%</InstallationType>"
   )
   echo !newLine!
)) > newFile.xml

Output with your example data:

<ConfigurationData>
<ReportsFolder>\Reports</ReportsFolder>
<Helpfolder>\Help</HelpFolder>
<InstallationType>New value</InstallationType>
<LicenseFolder>..\License</LicenseFolder>
</ConfigurationData>
like image 20
Aacini Avatar answered Oct 13 '22 10:10

Aacini