如何使用批处理匹配XML文件中的字符串并分配给变量? [英] How to match strings from an XML file using batch and assign to variable?

查看:108
本文介绍了如何使用批处理匹配XML文件中的字符串并分配给变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个XML文件(由第三方工具生成),其格式为

I have an XML file (generated by a third party tool) which is of format

<?xml version="1.0" encoding="UTF-8"?><ROOT test_count="22" test_fail_count="1" test_pass_count="21".......</ROOT>

所有内容都位于名称为Report.xml的文件的一行中.

All the content is in one line of the file with name Report.xml.

我一直在尝试编写批处理脚本

I have been trying to write a batch script

@echo off
setlocal EnableDelayedExpansion
set "Report="
for /f "delims=" %%x in (Report.xml) do set "Report=!Report! %%x"
REm set /p Report=< %Results_File%
echo report is !Report!
call:parseVal !Report!
exit/b

:parseVal
setlocal enableDelayedExpansion
set val="%~1"
echo %val%
echo !val!|findstr /rc:"test_count=.[0-9]*." >nul || (
    echo !val!
    EndLocal
    exit /b
)

rem ..

基本上,我试图从XML文件中获取test_count(22)test_fail_count(1)test_pass_count(21)的值.

Basically I am trying to grab values for test_count(22), test_fail_count(1) and test_pass_count(21) from the XML file.

关于如何实现这一目标的任何想法?

Any ideas on how to achieve this?

推荐答案

@ECHO Off
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "filename1=%sourcedir%\q42057260.txt"
SET "testcount="
SET "testfailcount="
FOR /f "usebackqdelims=" %%a IN ("%filename1%") DO (
 SET "xmlline=%%a"
 CALL :process
)

ECHO test count=%testcount% test fail count=%testfailcount%

GOTO :EOF

:process
:: dispose of awkward characters
SET "xmlline=%xmlline:?= %"
SET "xmlline=%xmlline:>= %"
SET "xmlline=%xmlline:<= %"
CALL :select %xmlline%
GOTO :EOF

:select
IF /i "%~1"=="" GOTO :EOF
IF DEFINED testcount IF DEFINED testfailcount GOTO :EOF
IF /i "%~1"=="test_count" SET /a testcount=%~2
IF /i "%~1"=="test_fail_count" SET /a testfailcount=%~2
SHIFT
GOTO select

GOTO :EOF

您需要更改sourcedir的设置以适合您的情况.

You would need to change the setting of sourcedir to suit your circumstances.

我使用了一个名为q42057260.txt的文件,其中包含您的数据用于测试.

I used a file named q42057260.txt containing your data for my testing.

将文件读取到%%a并传输到xmlline.

Read the file to %%a and transfer to xmlline.

使用:process来删除尴尬的字符(对cmd具有特殊含义的字符),方法是将每个字符替换为一个空格,然后将结果行作为参数列表传递给:select.

Use :process to remove awkward characters (those with a special meaning to cmd) by replacing each with a space, then pass the resultant line to :select as a parameter-list.

依次查看每个参数,去掉引号.当出现目标字符串时,将其存储变量设置为以下值.分配了两个值后,请纾困.

look at each parameter in turn, stripping quotes. When the target strings appear, set their storage variables to the following value. When both values are assigned, bail out.

并报告结果.

这篇关于如何使用批处理匹配XML文件中的字符串并分配给变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆