Solved Read a XML input from a Batch file and store in variables

July 12, 2014 at 06:54:51
Specs: Windows 7
I have been researching on how to read a xml input file into a batch file to read compare the data, but not had much luck.

This data will need then to be stored as a variable so we can compare the values.

There are a total of 4 values we need to measure, these are, temperature, ph, nh3 and o2

Because these values can change every hour when the data is pulled we need a way of comparing the data with a set value such as:

Is this possible?

Many thanks to all who responds.

I have included the xml file below:

See More: Read a XML input from a Batch file and store in variables

Report •

July 12, 2014 at 15:35:41
✔ Best Answer
Without examining your xml data, I have no way of knowing if the "spaces" shown in the jpg are truly spaces. They could be char. zeros or tabs, but I assumed spaces for this limited test on the limited data. (why didn't you post your xml, instead of that JPG stuff?)

@echo off & setlocal enabledelayedexpansion
for /f "tokens=1-5 delims=/><- " %%a in (riks.xml) do (
set %%a=%%b
if "%%b%%c%%d" equ "" if defined curr set %%a=!curr!
:: after testing, I concluded that the call to :xx is not actually needed
:: since the values compare correctly without it. So everything after
::this point is not necessary.
:: call "xx" with the var.s name: %1, followed by its current value: %2
for %%a in (temperature ph nh4 o2) do call :xx %%a !%%a!
goto :display

set z=!%1!
:: now the variable's value is adjusted to cirumvent decimals
set z=%z:.=%
set %1=%z%
echo var %1 -- value: !%1!
goto :eof

::this is just for confirmation that the var.s have the correct values.
echo temperature: %temperature%
echo pH: %ph%
echo nh4: %nh4%
echo o2: %o2%
:: simple test demonstration
if ph gtr 779 goto hi_ph
::or, using raw values:
if ph gtr 7.79 goto hi_ph
::====== end batch
and for the benefit of others, here's the xml data in text form:

<?xml version = "1.0"?>
-  <response>
  -  <temperature>
       < trend >O</trend>
  - <ph>
       <trend >O </trend >
  + <nh3>
  - <nh4>
  -  <o2>
  - <lux>
  -  <par>
  - <kelvin>

And I agree with Razor. XML is not handled well by batch. It usually results in frustration off the bat or problems down the road when things change, as they always do. Also, as demonstrated, it does not do math other than integers.

message edited by nbrane

Report •

July 13, 2014 at 09:01:50
It's best to not try XML processing by yourself, especially in CMD. Both VBScript and PowerShell have XML processing. There's also a 3rd party app to do XML in CMD, but I haven't personally tried it.

How To Ask Questions The Smart Way

Report •

Related Solutions

Ask Question