0

当我写这段代码时:

@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

我的代码有问题,我需要 "newLine=<SourceID>Admin</SourceID>"出现在 SelfBillingIndicator 上,但只出现在特定节点上。我在 xml 中有很多拥有 SelfBillingIndicator 的节点,我的程序替换了所有但我只需要替换内部<Invoice>节点。看例子:

<Document>
<SelfBillingIndicator>0</SelfBillingIndicator>
<Document>
<Invoice>
<InvoiceNo>F 2013A/321</InvoiceNo>
<SelfBillingIndicator>0</SelfBillingIndicator>
</Invoice>
4

2 回答 2

1

添加了在 finds和finds时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 应该逐节点解析。

并且您可以在同一行中有多个节点,或者一个节点可以使用几行。

如果您需要处理任意 XML 数据,我建议您考虑使用 + 解决方案。

于 2013-10-01T12:56:00.327 回答
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
于 2013-10-01T13:03:47.150 回答