<...">

Parse XML file for attribute from batch file

I am parsing an XML file as shown below:

<?xml version="1.0"?> <!-- --> <configuration> <settings> <connections> <connection name="name1" value="connection1" type="abc"/> <connection name="name2" value="connection2" type="def"/> </connections> </settings> </configuration> 

From the batch file, I offer the user a connection name. I want to parse the XML, get the connection with the specified name and get its value. Therefore, if the user gives the name1, I want to select connection1. I had the code below Retrieving XML tag values ​​(based on a flag) using a package

I am not familiar with the loop in the (especially delimits, tokens) batch file, so I'm not sure how this works and how to make it work for me.

 (for /F "tokens=1,2 delims== " %%a in (connection.config) do ( if "%%~b" neq "" set %%a=%%~b if /I "!name!" equ "%name%" echo !value! )) 
+4
source share
3 answers

It works if you use the correct tokens and delimiters:

 @echo off&setlocal for /F tokens^=2^,3^,5delims^=^<^"^= %%a in (connection.config) do ( if "%%a" equ "connection name" echo(%%b %%c ) 

Output:

 name1 connection1 name2 connection2 
+3
source
 @ECHO OFF SETLOCAL SET "name=name1" SET "connection=" SET "type=" for /F "tokens=5,7delims==/ " %%a in ( 'findstr /c:"<connection name=\"%name%\"" ^<connection.config' ) do SET connection=%%~a&SET type=%%~b ECHO connection=%connection% ECHO TYPE =%type% 

Search for a data string containing the literal string "\" escapes " ), then establish a connection with the 5th (and enter for good measure) from the seventh token of the data string

  <connection name="name1" value="connection1" type="abc"/> 

using = , / and [space] as delimiters.

+2
source

Here is xpath.bat -small script, which will allow you to get xml xpath values ​​without using external binaries:

 call xpath.bat "connection.config" "//connection/@name" call xpath.bat "connection.config" "//connection/@value" 
0
source

All Articles