3

I have a file called pictures.xml and it contains some pictures information like:

<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>

What I want do do is to get each line in for loop and print the names of the pictures. Sample output like:

  1. a.jpg - b.jpg c.jpg
  2. z1.jpg - z2.jpg z3.jpg z4.jpg

I can get each line but can't get the name attributes

    for /f "Delims=/" %%a in (pictures.xml) do ( 
        echo %%a
    )

1 Answer 1

1

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 output only something.jpg. Here the expülanation: First we split the file into lines. Now we want to find the something.jpg in each line and output only these tokens. So we can split the lines with " as delimeter and take the second substring. But we can't use " as delim because CMD won't accept this. That's why we first replace " with +. If + can appear in your code use a different character that is accepted as delimeter but won't be in your xml file.

Finally we can now split eacht line using + as delimeter and take the 2nd substring of each line which will result in only the file names.

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
        )
    )
)
Sign up to request clarification or add additional context in comments.

4 Comments

Is there a way that I can figure out if the current line contains ResourcePicture with a simple if statement as well?
"contains" is not that simple but you can check if it starts with "<ResourcePicture". I'll add the code to my answer.
Done. The key is SET prefix=!b:~1,15!. This skips the first char of the string and takes 15 chars starting with the second index so "<ResourcePicture Name="a.jpg">" becomes "ResourcePicture".
You are a pro! Thank you so much again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.