简体   繁体   English

读取.XML文件的特定标签之间的文本,并使用批处理文件将其显示在.txt文件中

[英]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: 我必须知道仅在“ config.xml”文件中存在的Jenkins版本,以下是其内容:

< 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. (我已经修改了xml行的语法,以便它可以作为平面文本显示)。我正在尝试在标签1.652之间提取版本号,并将“ 1.652”回显到.txt文件。

I'm a beginner and really did not find a specific code online to do it. 我是一个初学者,确实没有在线找到特定的代码来做。

The simple solution that directly answers question is to put this PowerShell one-liner into your .bat script: 直接回答问题的简单解决方案是将此PowerShell一线式放入.bat脚本中:

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. 这将使您的XML数据物化,选择第一个<version>标记的子文本节点,并将其值输出到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. 不过,对于已经将版本值写入.txt文件的情况,我有点怀疑。 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. 听起来您将要采用一些Rube Goldberg的复杂性级别,以将版本数据导出到文本文件,然后将值重定向回变量。 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. 如果要比较版本号和其他内容,请留在PowerShell中执行比较。

Here's a native PowerShell .ps1 script example: 这是一个本地PowerShell .ps1脚本示例:

[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. 这是为.bat脚本格式化的PowerShell衬里。 It uses exit [boolean] to set %ERRORLEVEL% for conditional execution (the && and || stuff). 它使用exit [boolean]设置%ERRORLEVEL%用于条件执行( &&||东西)。

@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.
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM