Parsing strings with batch script
I have a file called pictures.xml and it contains information about some of the images, for example:
<ResourcePicture Name="a.jpg">
<GeneratedPicture Name="b.jpg"/>
<GeneratedPicture Name="c.jpg"/>
</ResourcePicture>
<ResourcePicture Name="z1.jpg">
<GeneratedPicture Name="z2.jpg"/>
<GeneratedPicture Name="z3.jpg"/>
<GeneratedPicture Name="z4.jpg"/>
</ResourcePicture>
I want to do this to get each line for a loop and print the names of the images . Output example:
- a.jpg - b.jpg c.jpg
- z1.jpg - z2.jpg z3.jpg z4.jpg
I can get every line but cannot get the name attributes
for /f "Delims=/" %%a in (pictures.xml) do (
echo %%a
)
source to share
This should work:
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
FOR /F "tokens=*" %%a in (pictures.xml) DO (
SET b=%%a
SET b=!b:"=+!
FOR /F "delims=+ tokens=2" %%c in ("!b!") DO (
ECHO %%c
)
)
This will only output something.jpg
. Here's the expülanation: First we split the file into lines. Now we want to find something.jpg on each line and only print those tokens. This way we can split the strings by "
as a divisor and take the second substring. But we cannot use "
as delim because CMD won't accept it. Therefore, we first replace "
with +
. If it +
can appear in your code, use a different character that is accepted as a delimiter but will not appear in your XML file.
Finally, we can now split each line using +
as a divisor and take the second substring of each line, which will only result in filenames.
EDIT: Here's how to check if your line starts with "ResourcePicture":
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
for /f "tokens=*" %%a in (pictures.xml) do (
SET b=%%a
SET prefix=!b:~1,15!
IF !prefix!==ResourcePicture (
SET b=!b:"=+!
FOR /F "delims=+ tokens=2" %%c in ("!b!") DO (
ECHO %%c
)
)
)
source to share