Retrieving XML tag values ​​(based on flag) Using a batch

I am starting to write party scripts, and your help in this is greatly appreciated.

Below is the xml, and I need to extract all the names with the "on" flag in the txt file. There are several other instances of category tags.

<Head> <Category name="RIVERTD" flag="on" location="SG002"> </Category> <Category name="BRETRED" flag="on" location="IT213"> </Category> <Category name="AMERAND" flag="off" location="US212"> </Category> </Head> 

So, the conclusion I'm looking for is below

 RIVERTD BRETRED 

I tried using below code

 @echo off setlocal disableDelayedExpansion set input="CP.xml" set output="Names.txt" if exist %output% del %output% for /f "delims=" %%A in ('findstr /n /c:"name=" %input%') do ( set "ln=%%A" setlocal enableDelayedExpansion call :parseLine endlocal ) type %output% exit /b :parseLine set "ln2=!ln:*name=!" if "!ln2!"=="!ln!" exit /b for /f tokens^=2^ delims^=^" %%B in ("!ln2!") do ( setlocal disableDelayedExpansion >>%output% echo(%%B endlocal ) set "ln=!ln2!" goto :parseLine 

It gives me the result

 RIVERTD BRETRED AMERAND 

However, this code does not filter flag-based names. I am newbie. Please help add a flag based filter. Thank you very much.

0
source share
3 answers

This problem can be solved with a very interesting trick !:

 @echo off setlocal EnableDelayedExpansion (for /F "tokens=1,2 delims== " %%a in (CP.xml) do ( if "%%~b" neq "" set %%a=%%~b if /I "!flag!" equ "on" echo !name!& set flag= )) > Names.txt 

EDIT : some explanation

The file has several lines, but the OP looks for lines that have an assignment form, for example:

  name="RIVERTD" flag="on" name="BRETRED" flag="on" name="AMERAND" flag="off" 

My program does NOT check any name, but it executes any line with a value after the equal sign as an assignment. Thus, when my program processes the previous lines, the result is equivalent to executing the following commands:

  set name="RIVERTD" set flag="on" set name="BRETRED" set flag="on" set name="AMERAND" set flag="off" 

After that, just check if the FLAG variable is set to "on"; if so, then the variable NAME has a target value because it was assigned on the previous line.

Antonio

+1
source

That should do it for you.

 @echo off setlocal enabledelayedexpansion set "Name=" set "Flag=" set "Output=Names.txt" for /f "usebackq delims=" %%L in (`type "CP.xml"`) do ( for /f "usebackq tokens=1,2* delims= =<> " %%A in ('%%L') do ( if /i "%%~A"=="name" set "Name=%%~B" if /i "%%~A"=="flag" set "Flag=%%~B" if /i "%%~A"=="/category" ( if /i "!Flag!"=="on" echo.!Name!>>%Output% set "Name=" set "Flag=" ) ) ) endlocal pause 
+1
source

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

 call xpath.bat "CP.xml" "//Category[0]/@name" call xpath.bat "CP.xml" "//Category[1]/@name" 
+1
source

All Articles