从xml文件中提取值并使用批处理文件将其输出到csv

时间:2013-12-05 16:52:58

标签: xml batch-file

我需要从文件夹中所有xml文件中的特定xml标记中提取Value,并将值和文件名w / o ext导出到csv文件中的2个单独列中。我尝试了零运气。

xml看起来像这样:

<ICSMXML xmlns="http://www.icsm.com/icsmxml" version="1.0">
<Header>
<MsgDelivery>
  <To>
    <Credential>
      <Domain>ICSMID</Domain>
      <Identity>11</Identity>
    </Credential>
  </To>
  <From>
    <Credential>
      <Domain>DUNS</Domain>
      <Identity>039576814</Identity>
    </Credential>
  </From>
  <Sender>
    <Credential>
      <Domain>DUNS</Domain>
      <Identity>039576814</Identity>
    </Credential>
    <UserAgent />
  </Sender>
</MsgDelivery>
<MsgHeader>
  <MessageId>10000095713</MessageId>
  <Timestamp>04/12/2013 10:24:00 AM</Timestamp>

我需要在文件夹中找到的任何xml文件中解析MessageId中的值,然后将其与原始文件名w / o ext一起放入csv文件中。最好在第1列中使用值,在第2列中使用文件名w.o ext。

@echo off
call :check_lines < %1 > "%~N1.xml"
exit /b

REM Seek for the start of Data tag
:check_lines
set /P line=
if not "%line%" == "<MessageId>" goto check_lines

REM Copy until the end of Data tag
set /P line=
:put_lines
if "%line%" == "</MessageId>" goto end_lines
set /P line=%line% 
goto put_lines
:end_lines
echo %line%
>>Message.csv

1 个答案:

答案 0 :(得分:1)

这应该这样做:

@echo off
setlocal enabledelayedexpansion
for %%a in (*.xml) do (
call :XMLExtract "%%a" "<MessageID>" location
echo.!location!,%%~na
)
exit /b

:XMLExtract file keystart location
@echo off & setlocal
for /f "tokens=3 delims=<>" %%a in ('Findstr /i /c:%2 "%~1"') do (
   set "loc=%%a" & goto :endloop
)
:endLoop
ENDLOCAL & IF "%~3" NEQ "" (SET %~3=%loc%) ELSE echo.%loc%
exit /b