Edit XML with batch file

前端 未结 5 979
别那么骄傲
别那么骄傲 2021-01-06 06:41

I am wondering if there is any way to create a batch file that can edit a line in an XML document. The line would be identified by the preceding line. the idea would be as

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-06 07:06

    Excuse me. I apologize in advance for this post. I know this is a very old topic, but after read the answers here I couldn't resist the temptation to post this answer.

    The processing of a XML file via a Batch program is not just straightforward and direct, but in my humble opinion, easier than any equivalent solution in VBScript, PowerShell, etc. Here it is:

    @echo off
    setlocal EnableDelayedExpansion
    set "greater=>"
    set targetLine=Csetting name="BaseDirectory" serializeAs="String"!greater!
    echo Enter the new line to insert below target lines:
    set /P nextLine=
    setlocal DisableDelayedExpansion
    
    (for /F "delims=" %%a in (document.xml) do (
       set "line=%%a"
       setlocal EnableDelayedExpansion
       echo !line!
       if "!line!" equ "!targetLine!" echo !nextLine!
       endlocal
    )) > newDocument.xml
    

    The only problem with previous program is that it delete empty lines from the XML file, but this detail may be fixed in a very easy way by adding a couple commands more. Previous program may be modified to not check the complete line (as the OP originally requested), but check three parts in the same way of the last VBScript example:

    (for /F "delims=" %%a in (document.xml) do (
       set "line=%%a"
       setlocal EnableDelayedExpansion
       echo !line!
       set lineMatch=1
       if "!line:Csetting name=!" equ "!line!" set lineMatch=
       if "!line:BaseDirectoy=!" equ "!line!" set lineMatch=
       if "!line:serializeAs=!" equ "!line!" set lineMatch=
       if defined lineMatch echo !nextLine!
       endlocal
    )) > newDocument.xml
    

提交回复
热议问题