Sathish
Sathish

Reputation: 869

Windows batch file - replace a string in an XML file

I have the following XML file: input.xml

<?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 with ServerName using Windows Batch file programming.

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

Upvotes: 1

Views: 24699

Answers (2)

Reino
Reino

Reputation: 3423

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.

Xidel

xidel.exe -s "input.xml" -e "x:replace-nodes(//add[@value='Value2']/@value,attribute value {'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,^
    attribute value {'ServerName'}^
  )^
" --output-format=xml --output-declaration="<?xml version=\"1.0\"?>" --output-node-indent

XMLStarlet

xmlstarlet.exe ed -u "//add[@value='Value2']/@value" -v "ServerName" "input.xml"

Output in both cases:

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

Upvotes: 0

aikeru
aikeru

Reputation: 3983

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

Upvotes: 3

Related Questions