2013-02-26 96 views
0

我有一個XML文件,應該通過爲非XML標記中的項添加註釋來格式化該文件。示例輸入文件如下所示。批處理文件中的XML操作

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=^</book^> ^<^!--"'!'是否有逃避'!'符號的任何特殊的方式?

回答

0

你需要引用您的set S:

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

否則會有加引號並在其中被解釋爲重定向功能,你不想源轉義><

結果看起來不正確的是,雖然:

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

此外,有沒有任何理由你使用delims=¶?你是否真的期待在你的輸入中有一個字符?還是僅僅爲了不使用分隔符?在後一種情況下,delims=會這樣做。

+0

delims =¶是假的一。更改爲delims = – 2013-02-26 06:47:03

0

您的方法不正確,因爲它沒有在第一條評論(即您在開始時顯式插入它進行修補)之前插入開始註釋標記,並在文件末尾插入未封閉的開始註釋標記;此外,它不保留空行。下面的批處理文件正確地包圍任何文本之外<書... > < /書>標記爲註釋(與您的示例數據測試成功):

@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% 

安東尼