batch-file

Batch script to search & extract a string from a XML file


I have an XML file like this:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<configuration>
    <messaging msg="otherfiles.xml" />
    <counter tes="01" />
    <gate address="192.168.1.1:12345" allowed="172.11.1.1"/>
</configuration>

The file name is test.xml test.xml.

And I have an bat file:

@echo OFF
set dir="D:\Test"
for /f "delims=" %%i in ('findstr /i /c:"address" %dir%\test.xml') do call :job "%%i"
goto :eof

:job
set line=%1
set line=%line:/=%
set line=%line:<=+%
set line=%line:>=+%
set line=%line:*+string+=%
set line=%line:+=&rem.%
echo.%line%>>%dir%\output.txt

:eof

I need output like this:

192.168.1.1:12345

Can anyone help me?


Solution

  • You do not need to use all this search and replace, if you use delims and tokens with for:

    @echo off
    set "Mydir=D:\Test"
    for /f "tokens=1,2* delims==/" %%i in (
                 'findstr /c:"address" "%Mydir%\test.xml"'
                 ) do echo %%~j
    

    see for /?, from cmd for full usage information.

    Note! I changed your variable from %dir% to %Mydir% as it is not usually a good idea to name anything in batch the same as a system command.