使用批处理代码来批量xml格式化?

时间:2018-08-08 06:34:41

标签: xml batch-file format

我有一个包含50个子文件夹的文件夹,每个文件夹包含2个xml文件

O_DATA.xml
S_DATA.xml

由于它们出现在记事本中的一行中,因此我必须修复格式。


我从一个类似的问题中发现了以下代码:

@echo off
setlocal EnableDelayedExpansion

rem Create a variable with spaces
set "spaces= "
for /L %%i in (1,1,5) do set "spaces=!spaces!!spaces!"

rem Read the line
for /F "delims=" %%a in (input.txt) do set "line=%%a"

set level=0
:nextTag
   rem Separate first tag from line
   for /F "tokens=1* delims=<" %%a in ("!line!") do (
      set "tag=%%a"
      set "line=%%b"
   )
   rem Show first tag in one separate line
   if "%tag:~0,1%" equ "/" set /A level-=5
   echo !spaces:~0,%level%!^<!tag!
   if "%tag:~0,1%" neq "/" set /A level+=5
if defined line goto nextTag

Batch-Script for formatting XML-files | Search for Strings and comment them out

但这不是一回事,我也一直在研究这个答案,但我对批处理代码了解不多。

所以问题是如何制作将在该文件夹结构中运行的批处理脚本并将其格式化?

更新: 我尝试过:

C:\Users\user>for /d %%X in (C:\<C:\Users\user\Desktop\qq>\*)
do (c:\<C:\Users\user\Downloads\tidy-5.6.0-vc14-32b\tidy-5.6.0-vc14-
32b\bin>\tidy.exe -m -xml -config c:\<C:\Users\user\Downloads\tidy-5.6.0-
vc14-32b\tidy-5.6.0-vc14-32b\bin>\tidycfg.ini %%X\<O_DATA>.xml)

gives: %%X was unexpected at this time.

如果我删除一个%,则会给出:

< was unexpected at this time.

ini文件具有:

indent:yes
indent-attributes:yes

2 个答案:

答案 0 :(得分:1)

以下内容假定您的子文件夹都在qq目录中,并且您在提供的位置也使用tidy.exe

从批处理文件中:

@Echo Off
Set "FilePath=%UserProfile%\Desktop\qq"
Set "TidyPath=%UserProfile%\Downloads\tidy-5.6.0-vc14-32b\tidy-5.6.0-vc14-32b\bin"
For /D %%A In ("%FilePath%\*") Do For %%B In ("%%A\*.xml") Do "%TidyPath%\tidy.exe" -m -xml -i "%%B"

从命令提示符处:

For /D %A In ("%UserProfile%\Desktop\qq\*") Do For %B In ("%A\*.xml") Do "%UserProfile%\Downloads\tidy-5.6.0-vc14-32b\tidy-5.6.0-vc14-32b\bin\tidy.exe" -m -xml -i "%B"

答案 1 :(得分:0)

这是不需要外部工具安装的一种方式(我在某种程度上使用了Compo的答案):

@echo Off

Set "FilesPath=%UserProfile%\Desktop\qq"

for /D %%A in ("%FilesPath%\*") do (
    for %%B In ("%%A\*.xml") do (
        call ::beautifyXml "%%~fB"
    )
)


exit /b %errorlevel%

::::::::::::::::::
:beautifyXml
@echo off
powershell "function fx($xml, $i=2){$SW=New-Object System.IO.StringWriter;$XW=New-Object System.XMl.XmlTextWriter $SW; $XW.Formatting='indented';$XW.Indentation=$i;([xml]$xml).WriteContentTo($XW);$XW.Flush();$SW.Flush();Write-Output $SW.ToString();};FX (gc -path """%~f1""") -i 4">"%~dp1~"
move /y "%~dp1~" "%~f1" >nul 2>nul
goto :eof

它不会检查文件是否具有有效的xml语法,这会损害其内容,因此请提前备份,以防万一。