'Read xml from batch

I am trying to read an xml file using a batch (.bat) file and have searched multiple sites without a successful solution.

XML file structure:

<parameter>
<name>myname</name>
<value>1234</value>
</parameter>

Attempted batch code:

FOR /f "tokens=2 delims=<>" %%i in ('type "sample.xml" ^|find "myname"') do set "value=%%i"
echo %value%

... And then repeats with each one having its own name and value.

What I want to do is get the value using the name as the search criteria.

I can't share what I have tried as I am using my phone to send this.



Solution 1:[1]

The core point of your problem is that you want to get the next line after the one you located. There are a lot of methods to achieve this. The next one is a pretty simple one:

for /F "delims=:" %%i in ('findstr /N "myname" sample.xml') do set "lines=%%i"
for /F "skip=%lines% tokens=2 delims=<>" %%v in (sample.xml) do set "value=%%v" & goto next
:next
echo %value%

Of course, if the .xml file have a different format, this method will not work...


Here it is a complete test. THis is the program test.bat:

@echo off
setlocal

for /F "delims=:" %%i in ('findstr /I /N "%~1" sample.xml') do set "lines=%%i"
for /F "skip=%lines% tokens=2 delims=<>" %%v in (sample.xml) do set "value=%%v" & goto next
:next
echo %value%

This is the sample.xml file I used in the test:

<parameter>
<name>myName</name>
<value>Antonio</value>
</parameter>
<parameter>
<name>myDate</name>
<value>2022/02/24</value>
</parameter>
<parameter>
<name>myTime</name>
<value>12:13:14</value>
</parameter>

And this is the test:

C:\Users\Antonio\Documents\test> test myName
Antonio

C:\Users\Antonio\Documents\test> test myDate
2022/02/24

C:\Users\Antonio\Documents\test> test myTime
12:13:14

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1