当我写这段代码时:
@echo off
setlocal EnableDelayedExpansion
set anotherVariable=New value
(for /F "delims=" %%a in (2.xml) do (
set "line=%%a"
set "newLine=!line:SelfBillingIndicator>=!"
if "!newLine!" neq "!line!" (
set "newLine=!line!"
echo !newLine!
set "newLine=<SourceID>Admin</SourceID>"
)
@echo !newLine!
)) > 3.xml
我的代码有问题,我需要在SelfBillingIndicator上显示"newLine=<SourceID>Admin</SourceID>"
,但仅限于特定节点。我有很多关闭xml的节点有SelfBillingIndicator,我的程序替换所有,但我只需要替换内<Invoice>
节点。看一下这个例子:
<Document>
<SelfBillingIndicator>0</SelfBillingIndicator>
<Document>
<Invoice>
<InvoiceNo>F 2013A/321</InvoiceNo>
<SelfBillingIndicator>0</SelfBillingIndicator>
</Invoice>
答案 0 :(得分:1)
添加了变量inside_Invoice
,当找到1
时会变<Invoice>
,0
时会变</Invoice>
。
然后,仅在inside_Invoice==1
:
@echo off
setlocal EnableDelayedExpansion
set anotherVariable=New value
SET inside_Invoice=0
(for /F "delims=" %%a in (2.xml) do (
set "line=%%a"
IF "%%a"=="<Invoice>" SET inside_Invoice=1
IF "%%a"=="</Invoice>" SET inside_Invoice=0
SET "newLine=%%a"
IF !inside_Invoice!==1 set "newLine=!line:SelfBillingIndicator>=!"
if "!newLine!" neq "!line!" (
set "newLine=!line!"
echo !newLine!
set "newLine=<SourceID>Admin</SourceID>"
)
@echo !newLine!
)) > 3.xml
编辑:有时,我们最好重写一切......
@echo off
setlocal EnableDelayedExpansion
SET inside_Invoice=0
(for /F "delims=" %%a in (2.xml) do (
ECHO.%%a
IF "%%a"=="<Invoice>" (
SET inside_Invoice=1
) ELSE IF "%%a"=="</Invoice>" (
SET inside_Invoice=0
) ELSE IF !inside_Invoice!==1 (
ECHO "%%a"|FIND "<SelfBillingIndicator>">NUL&&ECHO ^<SourceID^>Admin^</SourceID^>
)
))>3.xml
编辑:正如我告诉你的那样,“批处理XML解析很棘手”!
@echo off
setlocal EnableDelayedExpansion
SET inside_Invoice=0
(for /F "delims=" %%a in (2.xml) do (
ECHO.%%a
ECHO "%%a"|FIND "<Invoice>">NUL&&SET inside_Invoice=1
ECHO "%%a"|FIND "</Invoice>">NUL&&SET inside_Invoice=0
IF !inside_Invoice!==1 ECHO "%%a"|FIND "<SelfBillingIndicator>">NUL&&ECHO ^<SourceID^>Admin^</SourceID^>
))>3.xml
注意(此)批次立即检查完整行。应该逐节点地解析XML。
您可以在同一行中有多个节点,或者一个节点可以使用多行。
答案 1 :(得分:0)
@echo off
setlocal EnableDelayedExpansion
set anotherVariable=New value
set inInvoice=false
(for /F "delims=" %%a in (2.xml) do (
set "line=%%a"
set "newLine=!line:SelfBillingIndicator>=!"
if "!newLine!" neq "!line!" (
if "!inInvoice!" equ "true" (
set "newLine=!line!"
echo !newLine!
set "newLine=<SourceID>Admin</SourceID>"
)
) else if "!line!" equ "<Invoice>" (
set inInvoice=true
) else if "!line!" equ "</Invoice>" (
set inInvoice=false
)
@echo !newLine!
)) > 3.xml