用于格式化 XML 个文件的批处理脚本 |搜索字符串并将其注释掉

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

所以我有一个 XML-File,它没有格式化,这意味着它只有一行。我遇到的问题是,我想删除两行或将它们注释掉。

有没有办法使用批处理脚本来格式化 XML 文件,所以如果我有:

<xml><tag><othertag></othertag></tag></xml>

输出将是

<xml>
     <tag>
          <othertag>
          </othertag>
     </tag>
</xml>

或者,如果我只有一个模式,并且不能使用 findstr /v,我怎么能 replace/add 字符串呢,因为我只有一行?

提前致谢!

@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

输出:

<xml>
     <tag>
          <othertag>
          </othertag>
     </tag>
</xml>

请注意,可以通过这种方式处理的行的最大长度约为 8150 个字符。此外,此解决方案从文件中删除所有感叹号。如果需要,这两个点都可以固定。

试试这个:

@echo off

call ::beautifyXml c:\some.xml

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