Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read XML file with windows batch

I'm trying to read an xml file and read STRING "50" between the build tags from a XML file. I tried it but I'm not getting any output.

The XML file..

    <?xml version="1.0" encoding="UTF-8"?>
    <CDMDataXML xmlns="http://www.avocent.org/trellis/CDMLoaderXMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.avocent.org/trellis/CDMLoaderXMLSchema CDMLoaderXMLSchema.xsd">
<CDMDataVersion>
    <Major>1</Major>
    <Minor>0</Minor>
    <Build>50</Build>
    <Delimiter>.</Delimiter>
</CDMDataVersion>

The batch file code..

@ECHO OFF
SETLOCAL
SET "build="&SET "grab="
FOR /f "tokens=*" %%a IN (version.xml) DO (
IF DEFINED grab SET build=%%a&SET "grab="
IF /i "%%a"=="<BUILD>" SET grab=Y
)
ECHO found build=%build%
GOTO :EOF

Will the code run if the xml file and the batch file are situated in the same folder and i execute the batch file from cmd???

EDIT 1:

@MC ND I made the changes you mentioned and ran the code.When i hit enter, the cursor moves to the next line and gets stuck there.I doesn't give any output as well. I'm not able to close the cmd window also. All this is explained in the image file below.

file

ANSWER

As suggested by MCND below I renamed my file to findx.bat which is returning the value "50" which is what i wanted.The screen-shot of the correct output is given below.

ans

Thanks a lot @MCND!!

like image 949
Lucy Avatar asked May 22 '26 10:05

Lucy


2 Answers

Retrieve only the required line (find), and using the adecuated delimiters (<>), tokenize the line to retrieve the required information

     delims:    v     v  v      v
     line  :    <Build>50</Build>
     tokens:^1   ^2    ^3 ^4

Now, translate this into code

@echo off
    setlocal enableextensions disabledelayedexpansion

    set "build="
    for /f "tokens=3 delims=<>" %%a in (
        'find /i "<Build>" ^< "file.xml"'
    ) do set "build=%%a"

    echo %build%
like image 112
MC ND Avatar answered May 25 '26 00:05

MC ND


you can try the xpath.bat - script that can get a value from xml file by given xpath:

call xpath.bat "build.xml" "\\build"
like image 43
npocmaka Avatar answered May 24 '26 23:05

npocmaka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!