user3058775
user3058775

Reputation: 69

Batch Program IF THEN help needed

I have an XML file to read, and certain nodes I already have parsed. Here is an example:

 <goingTo>RNS</goingTo>
 <goingTo>HTY</goingTo>

The cmd code to extract from the XML file looks like this:

 for /F "tokens=3 delims=<>" %%i in ('findstr "<goingTo>" AST.xml') do echo %%i >>To_Places.txt

This all works fine, with a result of:

RNS
HTY 

in my To_Places.txt file.

Also in my XML I am trying to parse and add conditional statements, but I am having a hard time with that.

In my XML file I have to iterate through the file to check if something is loaded or empty.

A snippet of the node in XML:

 <VehWeight>14.878</VehWeight>
 <VehWeight>4.98</VeWeight>

I need the batch code to look through the XML file, read the VehWeight data and execute GTR 14 = Load or LSS 14 = MTY. Then have this output to a text file appended to the To_Places.txt file.

Is there such a way in batch?

Upvotes: 0

Views: 77

Answers (1)

rojo
rojo

Reputation: 24476

When reading or manipulating XML, it's always better to treat it as structured XML, rather than trying to hack and scrape it as text with token delimiters or regular expressions. That way, regardless of whether the XML is beautified or uglified, it still works.

I like to use JScript for this sort of thing. It's very easy to include as hybrid code in a .bat file, and it handles document object model navigation easily (just as JavaScript does).

Save this with a .bat extension and run it. See whether it gives you the results you expect.

@if (@CodeSection == @Batch) @then

@echo off
setlocal

set "XMLfile=AST.xml"
set "outfile=To_Places.txt"

cscript /nologo /e:JScript "%~f0" "%XMLfile%" "%outfile%" && echo Done.

goto :EOF
@end // end batch / begin JScript chimera

var fso = WSH.CreateObject('Scripting.FileSystemObject'),
    DOM = WSH.CreateObject('Microsoft.XMLDOM'),
    args = { xmlfile: WSH.Arguments(0), outfile: WSH.Arguments(1) };

DOM.load(args.xmlfile);
DOM.async = false;
DOM.setProperty('SelectionLanguage', 'XPath');

if (DOM.parseError.errorCode) {
    var e = DOM.parseError;
    WSH.StdErr.WriteLine('Error in ' + args.xmlfile + ' line ' + e.line + ' char '
        + e.linepos + ':\n' + e.reason + '\n' + e.srcText);
    WSH.Quit(1);
}

var out = fso.CreateTextFile(args.outfile, 1);

for (var d = DOM.selectNodes('//goingTo/text()'), i = 0; i < d.length; i++)
    out.WriteLine(d[i].nodeValue);

for (var d = DOM.selectNodes('//VehWeight/text()'), i = 0; i < d.length; i++)
    out.WriteLine(d[i].nodeValue * 1 < 14 ? 'MTY' : 'LOAD');

out.Close();

Upvotes: 1

Related Questions