开发者

Batch file for loop removes xml comment nodes

开发者 https://www.devze.com 2023-02-26 15:15 出处:网络
when I parse an xml file for开发者_JAVA百科 processing in a batch job, the comment nodes seem to be altered; is this something to do with special characters? how do I prevent it.

when I parse an xml file for开发者_JAVA百科 processing in a batch job, the comment nodes seem to be altered; is this something to do with special characters? how do I prevent it.

A node like this: <!--Location: D:\\Logs--> will look like this when queried through %%G: < D:\\Logs-->

A small code sample:

        **setLocal EnableDelayedExpansion
    for /f "usebackq tokens=* delims= " %%G in ("%HOMEDRIVE%\Logs\Connections.xml") do (

            set str=%%G     

        echo !str!

            PAUSE

    )

endlocal

    **


You got three problems.

  1. With delayed expansion, it removes/handles the ! and carets ^ as special characters, as the ! is evaluated after the expansion of the for-loop-var %%G
  2. Some text can't be displayed with a simple echo, like OFF, ON or /?
  3. Empty lines are removed, as a FOR-Loop don't handle them

To solve 1. you should use the delayed toggling trick To solve 2. you could use the echo( form.

So you get

setLocal DisableDelayedExpansion
for /f "usebackq tokens=* delims=" %%G in ("%HOMEDRIVE%\Logs\Connections.xml") do (
    set "str=%%G"
    setLocal EnableDelayedExpansion
    echo(!str!
    endlocal
)

If you want to solve 3. (empty lines), you could use findstr /n to number all lines, so no line is empty, and then remove the number in the loop.

setLocal DisableDelayedExpansion
for /f "usebackq tokens=* delims=" %%G in (`findstr /n "^" "list.txt"`) do (
    set "str=%%G"
    setLocal EnableDelayedExpansion
    echo(!str:*:=!
    endlocal
)
0

精彩评论

暂无评论...
验证码 换一张
取 消