问题
I have a folder that contains 50 subfolders each one of these contains 2 xml files
O_DATA.xml
S_DATA.xml
Since they appear in one line in Notepad, I have to fix the formatting.
I have found from a similar question here this code:
@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
But it is not really the same thing and also I've been studying this answer but I don't know much about batch code.
So the question is how to make a batch script that will run through that folder structure and format them?
Update: I tried this:
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.
and if I delete one % gives:
< was unexpected at this time.
the ini file has:
indent:yes
indent-attributes:yes
回答1:
The following assumes that your subfolders are all inside the qq directory, and you are using tidy.exe, also in the location provided.
From a batch file:
@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"
From the Command Prompt:
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"
回答2:
Here's a way that does not need external tool installations (I'm partially using the Compo's answer):
@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
It does not checks if the files have valid xml syntax which can harm their content so back-up in advance just in case.
来源:https://stackoverflow.com/questions/51740005/using-batch-code-to-mass-xml-formatting