1

I have the following XML file:

<?xml version="1.0"?>
    <configuration>
      <startup>
        <supportedRuntime version="v2.0.50727"/>
      </startup>
      <appSettings>
        <add key="Name1" value="Value1"/>
        <add key="Name2" value="Value2"/>
        <add key="Name3" value="Value3"/>
      </appSettings>
      <runtime>
        <legacyUnhandledExceptionPolicy enabled="true"/>
      </runtime>
    </configuration>

I need to replace "Value2" to "ServerName" using Windows Batch file programming.

Could anybody help one as I am new to Windows Batch programming?

Andriy M
  • 76,112
  • 17
  • 94
  • 154
Sathish
  • 869
  • 2
  • 13
  • 28
  • Any specific reason why it HAS to be a bat file, and not a small C program? – Radu Nov 02 '11 at 06:59
  • my requirement is given such a way to write a batch file :( – Sathish Nov 02 '11 at 07:02
  • 1
    Look at this post1 in stackoverflow which has the required answer. http://stackoverflow.com/questions/60034/how-can-you-find-and-replace-text-in-a-file-using-the-windows-command-line-envir – Raghuram Nov 02 '11 at 07:04
  • 1
    DOS is an operating system that hasn't been in active use for a very long time. Your question is in fact about *Windows* batch scripting. Even though it originated in DOS times, it was Windows (esp. Windows NT) where it acquired a lot of additional features. – Andriy M Nov 02 '11 at 14:38

2 Answers2

3

Batch will have trouble with <, >, ^ and & characters. This will work, but a JScript/VBScript script (like is referenced in one of the comments) is a much better solution.

Change "ORIGINAL" to the text being searched for, and "REPLACE" to the new text. I recommend for Windows scripting to learn JScript.

@echo off
for /f "tokens=* delims=" %%f in ('type sometext.txt') do CALL :DOREPLACE "%%f"

GOTO :EOF
:DOREPLACE
SET INPUT=%*
SET OUTPUT=%INPUT:ORIGINAL=REPLACE%

for /f "tokens=* delims=" %%g in ('ECHO %OUTPUT%') do ECHO %%~g>>out.txt

EXIT /b

:EOF
aikeru
  • 3,773
  • 3
  • 33
  • 48
0

Batch doesn't support XML and doesn't come with an XML-parser, so without having to resort to hacks I would highly recommend a third-party XML-parser like or instead.

xmlstarlet.exe ed -u "//add[@value='Value2']/@value" -v "ServerName" input.xml
xidel.exe -s input.xml -e "x:replace-nodes(//add[@value='Value2']/@value,function($x){attribute {name($x)} {'ServerName'}})" --output-format=xml --output-declaration='^<?xml version="1.0"?^>' --output-node-indent

xidel.exe -s input.xml -e ^"^
  x:replace-nodes(^
    //add[@value='Value2']/@value,^
    function($x){attribute {name($x)} {'ServerName'}}^
  )^
" --output-format=xml --output-declaration='^<?xml version="1.0"?^>' --output-node-indent
Reino
  • 3,203
  • 1
  • 13
  • 21