這是純粹的batch-file解決方案。以下腳本需要三個命令行參數:XML文件(的路徑),節點(示例中的slideshow
)和屬性名稱(date
),按給定順序排列。返回數據輸出到控制檯窗口,並可以重定向到一個文件(>
)。
這是一個示例命令行運行腳本(假設該XML文件被稱爲presentation.xml
,腳本被命名爲extract-xml-attrib.bat
並將所得數據是要被寫入到attr.txt
):
"extract-xml-attrib.bat" "presentation.xml" "slideshow" "date" > "attr.txt"
這是腳本代碼extract-xml-attrib.bat
:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "XML=%~1"
set "TAG=%~2"
set "PAR=%~3"
rem // Define defaults here:
if not defined XML set "XML=presentation.xml"
if not defined TAG set "TAG=slideshow"
if not defined PAR set "PAR=date"
set "FLAG="
for /F usebackq^ delims^=^ eol^= %%L in ("%XML%") do (
set "LINE=%%L"
setlocal EnableDelayedExpansion
set "REST=!LINE:*<%TAG%=!"
if not defined REST (
set "FLAG=#"
) else (
set "REST=!LINE:*<%TAG% =!"
if not "!REST!"=="!LINE!" (
set "FLAG=#"
) else (
set "REST=!LINE:*<%TAG% =!"
if not "!REST!"=="!LINE!" (
set "FLAG=#"
)
)
)
for /F "tokens=1,2 delims=>" %%E in ("!REST!/") do (
if defined FLAG (
endlocal
set "FLAG=#"
) else (
endlocal
)
set "REST=%%E"
if defined FLAG (
call :GET_ATTR "REST:~,-1" "%PAR%"
)
if not "%%F"=="" (
set "FLAG="
)
setlocal EnableDelayedExpansion
)
endlocal
)
endlocal
exit /B
:GET_ATTR var_string param_name
setlocal DisableDelayedExpansion
set "PAR=%~2"
setlocal EnableDelayedExpansion
set "STR=!%~1!"
set "NEXT="
for %%S in (!STR!) do (
if defined NEXT (
endlocal
echo(%%~S
set "NEXT="
setlocal EnableDelayedExpansion
)
set "STR=!STR:*%%S=!"
if "%%S"=="%PAR%" (
if defined STR (
if "!STR:~,1!"=="=" (
if "!STR:~1,1!"==" " (
echo(
) else if "!STR:~1,1!"==" " (
echo(
) else (
set "NEXT=#"
)
)
)
)
)
if defined NEXT echo(
endlocal
endlocal
exit /B
純批處理腳本不能解析XML文件;我推薦使用本地支持XML的語言(PowerShell,VBScript,JavaScript等?);如果你確實需要一個批處理文件,你甚至可以嵌入另一種語言;如果你不想要這個,你需要讀取XML文件作爲正常文本... – aschipfl