Search code examples
xmlwindowsfilebatch-fileinsert-update

update xml file with batch


  1. I have been searching for an hour with no luck
  2. My boss wants it to be a batch file

I have a xml file that contains the following.

    <?xml version="1.0"?>
    <profiledoc default="*** Last Run ***">
    <profile name="*** Last Run ***" >
    <workingdir>c:\proj</workingdir>
    <somestuff>none</somestuff>
    <smpnumprocs>4</smpnumprocs>
    <otherstuff></otherstuff>
    <llama>FLUFFY</llama>
    <language>en-us</language>
    <customexe></customexe>
    <addlparams></addlparams>
    <graphicsdevice>win32</graphicsdevice>
    </profile>
    </profiledoc>

We want to set <smpnumprocs>4</smpnumprocs> (which is the number of processors used) to 2 therefore, the line should look like this <smpnumprocs>2</smpnumprocs>

I figured out how to get to the value I want with this

FOR /f "tokens=3 delims=><  " %%a IN ('TYPE %LOCAL_FILE% ^| FIND "<smpnumprocs>"') DO SET NUM_PROCS=%%a

Now how do I change the value?


Solution

  • You can use script I wrote:

    @echo OFF
    @setlocal ENABLEDELAYEDEXPANSION
    
    if "%~1" == "" (
        echo Please provide xml file path as a first parameter.
        exit /B 1
    )
    
    if not exist "%~1" (
        echo Xml file with given path does not exist.
        exit /B 2
    )
    
    if exist "%~1.tmp" del /F /Q "%~1.tmp"
    
    for /F "delims=" %%G in (%~1) do (
        set LINE=%%G
        if not "!LINE!" == "!LINE:smpnumprocs=!" (
            set LINE=!LINE:4=2!
        )
        >> "%~1.tmp" echo !LINE!
    )
    
    del /F /Q "%~1"
    ren "%~1.tmp" "%~1"
    
    @endlocal
    

    Script scans through given xml file and finds line with smpnumprocs in it. If that kind of line is found, it substitutes 4 to 2.

    All lines are dumped to <xmlFilePathHere>.tmp file, which replaces original file at the end.