如何使用批处理脚本逐个标记(Pretty Print)格式化XML?

时间:2018-11-10 17:26:16

标签: xml batch-file formatting

假设我在一个文件中使用以下格式:

         `<xml><tag><othertag>ABC</othertag></tag></xml>`

但是我需要下面的格式化输出:

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

此格式的输出我需要其他文件中的

帮助我使用批处理脚本,它将能够进行这种格式化。

2 个答案:

答案 0 :(得分:0)

尝试一下(它不会检查xml是否具有有效的语法):

call ::beautifyXml "c:\some.xml"
call ::beautifyXml "c:\some.xml" > "c:\new.xml"

exit /b %errorlevel%


:beautifyXml
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"
goto :eof

如果新文件看起来正常,则可以添加其他移动命令来替换旧文件。

答案 1 :(得分:0)

不应通过批处理文件处理XML文件。但是,这个特定示例为我提供了使用批处理文件获得一些乐趣的机会,它可以工作! ;)

@echo off
setlocal EnableDelayedExpansion

for /F "tokens=2 delims=`" %%a in (input.txt) do set "format=%%a"

for /F %%a in ('copy /Z "%~F0" NUL') do set NL=%%a^
% Don't remove %
% these lines  %
set "SP=    "
set "format=%format:></=>^!NL^!^!SP:~0,-8^!" ^& set "SP=^!SP:~0,-4^!" ^& set /P "=</%"
< NUL (set /P "=%format:><=>!NL!!SP!" & set "SP=    !SP!" & set /P "=<%" & echo/) > output.txt

输出:

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

有关所用方法的说明,请参见this thread