Ruqsar Shalu
Ruqsar Shalu

Reputation: 1

Read text between specific tag of .XML file and display it in a .txt file using batch file

I have to know the Jenkins version which is only present in the 'config.xml' file, below are the contents of it:

< version > 1.652 < / version > 

(I have modified the syntax of the xml line so that it is visible as plane text) I'm trying to pull the version number between the tags 1.652 and echo "1.652" to a .txt file.

I'm a beginner and really did not find a specific code online to do it.

Upvotes: 0

Views: 472

Answers (1)

rojo
rojo

Reputation: 24466

The simple solution that directly answers question is to put this PowerShell one-liner into your .bat script:

powershell "([xml](gc config.xml)).SelectSingleNode('//version/text()').data" >out.txt

That will objectify your XML data, select the child text node of the first <version> tag, and output its value to out.txt.

I'm a little suspicious about your writing the version value to a .txt file, though, when it's already written in config.xml. Is that necessary? It sounds like you're about to employ some Rube Goldberg level of complexity to export the version data to a text file then redirect the value back into a variable. If that's what you're planning, that's more complicated than it needs to be. If you're comparing the version number against something, stay in PowerShell to perform the comparison.

Here's a native PowerShell .ps1 script example:

[version]$minimumVer = "1.652"
[version]$jenkinsVer = ([xml](gc config.xml)).SelectSingleNode('//version/text()').data

if ($minimumVer -gt $jenkinsVer) {
    "Fail.  Jenkins must be version $minimumVer or newer for this to work."
}
else {
    "Happiness and rainbows."
}

Here's a PowerShell one(ish)-liner formatted for a .bat script. It uses exit [boolean] to set %ERRORLEVEL% for conditional execution (the && and || stuff).

@echo off & setlocal

set "minVersion=1.652"

set "psCmd=powershell "exit ([version](([xml](gc config.xml)).SelectSingleNode(^
'//version/text()').data) -ge [version]'%minVersion%')""

%psCmd% && (
    echo Fail.  Jenkins must be version %minVersion% or newer for this to work.
) || (
    echo Happiness and rainbows.
)

Upvotes: 1

Related Questions