【问题标题】:XML manipulation in batch file批处理文件中的 XML 操作
【发布时间】:2013-02-27 22:43:34
【问题描述】:

我有一个 XML 文件,应该通过为非 XML 标记中的项目添加 cmets 来很好地格式化该文件。示例输入文件如下所示。

comment 1
<book id=1>
    Book 1
</book>

comment 2
<book id=2>
    Book 2
</book>

comment 3
<book id=3>
    Book 3
</book>

预期输出

<!-- comment 1 -->
<book id=1>
    Book 1
</book>

<!-- comment 2 -->
<book id=2>
    Book 2
</book>

<!-- comment 3 -->
<book id=3>
    Book 3
</book>

编写的批处理脚本。

@ECHO off
SETLOCAL enabledelayedexpansion

SET INTEXTFILE=test.xml
SET OUTTEXTFILE=out.xml

SET "SEARCH_TEXT_1=^<book "
SET "REPLACE_TEXT_1=--^> ^<book "

SET "SEARCH_TEXT_2=^</book^>"
SET "REPLACE_TEXT_2=^</book^> ^<^!--"

SET "comment=<^!--- Converted to well formed XML --> <^!--"
ECHO !comment! > %OUTTEXTFILE%

for /f "tokens=1,* delims=¶" %%A in ( '"type %INTEXTFILE%"') do (
    SET string=%%A
    SET modified=!string:%SEARCH_TEXT_1%=%REPLACE_TEXT_1%!
    SET modified=!modified:%SEARCH_TEXT_2%=%REPLACE_TEXT_2%!
    ECHO !modified! >> %OUTTEXTFILE%
)

错误:

< was unexpected at this time.

这是由于SET "REPLACE_TEXT_2=^&lt;/book^&gt; ^&lt;^!--" 行中的'!' 导致'!' 符号转义有什么特殊的方法吗?

【问题讨论】:

    标签: windows batch-file


    【解决方案1】:

    您需要引用您的sets:

    SET "string=%%A"
    SET "modified=!string:%SEARCH_TEXT_1%=%REPLACE_TEXT_1%!"
    SET "modified=!modified:%SEARCH_TEXT_2%=%REPLACE_TEXT_2%!"
    

    否则在源代码中会有未引用和未转义的&gt;&lt;,它们被解释为重定向,这是您不想要的。

    结果看起来还不太对劲:

    <!--- Converted to well formed XML --> <!-- 
    comment 1--
    <book id=1>--
        Book 1--
    </book>--
    ...
    

    另外,您使用delims=¶ 有什么原因吗?您是否真的期待输入中的 字符?还是只是为了不使用分隔符?在后一种情况下,delims= 会这样做。

    【讨论】:

    • delims=¶ 是虚拟的。改为 delims=
    【解决方案2】:

    您的方法不正确,因为它没有在第一个注释之前插入开始注释标记(您通过在开头显式插入它来修补),并在文件末尾插入一个未关闭的开始注释标记;此外,它不保留空行。下面的批处理文件正确地将 标记之外的任何文本包含在注释中(使用您的示例数据成功测试):

    @echo off
    setlocal DisableDelayedExpansion
    set bang=!
    setlocal EnableDelayedExpansion
    
    set inFile=test.xml
    set outFile=out.xml
    
    set "startLine=<book "
    set startLen=6
    set "endLine=</book>"
    
    echo ^<!bang!--- Converted to well formed XML --^> > %outFile%
    
    set inBook=
    (for /F "tokens=1* delims=:" %%a in ('findstr /N "^" %inFile%') do (
       set string=
       set "string=%%b"
       if not defined string (
          echo/
       ) else (
          if "!string:~0,%startLen%!" equ "%startLine%" (
             set inBook=true
          )
          if not defined inBook (
             echo ^<!bang!-- !string! --^>
          ) else (
             echo !string!
             if "!string!" equ "%endLine%" (
                set inBook=
             )
          )
       )
    )) >>  %outFile%
    

    安东尼奥

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-08
      相关资源
      最近更新 更多