1

I'm trying to remove a parent section using a string in a child's tag.

Section of the XML file (original.xml)

<Mods>
    <ModItem>
        <Name>296707746.sbm</Name>
        <PublishedFileId>296707746</PublishedFileId>
    </ModItem>
    <ModItem>
        <Name>294620323.sbm</Name>
        <PublishedFileId>294620323</PublishedFileId>
    </ModItem>
    <ModItem>
        <Name>295393216.sbm</Name>
        <PublishedFileId>295393216</PublishedFileId>
    </ModItem>
</Mods>

I need to remove the parent section of a child that matches <Name>numbers.sbm</Name> tags Like this:

<ModItem>
    <Name>294620323.sbm</Name>
    <PublishedFileId>294620323</PublishedFileId>
</ModItem>

to produce this:

<Mods>
    <ModItem>
        <Name>296707746.sbm</Name>
        <PublishedFileId>296707746</PublishedFileId>
    </ModItem>
    <ModItem>
        <Name>295393216.sbm</Name>
        <PublishedFileId>295393216</PublishedFileId>
    </ModItem>
</Mods>

Current code i'm using:

FOR /f "tokens=1 delims=:" %%L in ('FINDSTR /n "<Name>294620323.sbm</Name>"      sandboxxml.txt ') do set /a line=%%L-2

BREAK> "%temp%\empty"

FC "%temp%\empty" "sandboxxml.txt" /lb %line% /t | MORE +4 |FINDSTR /b /e /v "*****" >temp.xml

(the code is a modified answer from a different topic)

It adds everything before the section to temp.xml

How would i get the rest of the original.xml into temp.xml, excluding the removed section?

and is there a different/simpler way to achieve this?

( this is my first question on stackoverflow, sorry if i did something wrong!)

generalwrex
  • 13
  • 1
  • 2
  • 5

2 Answers2

1

The Batch file below use the same method of your example:

@echo off
setlocal 

for /F "delims=:" %%L in ('findstr /N "<Name>294620323.sbm</Name>" original.xml') do set /A start=%%L-1, end=%%L+2
(for /F "tokens=1* delims=:" %%a in ('findstr /N "^" original.xml') do (
   if %%a lss %start% echo(%%b
   if %%a gtr %end% echo(%%b
)) > new.xml

Note that this method works on this file only, with this specific format.

Aacini
  • 65,180
  • 12
  • 72
  • 108
1

It can be done very efficiently with a one liner using a hybrid JScript/Batch utility called REPL.BAT that performs a regular expression search/replace on stdin and writes the result to stdout. It is pure script that will work on any modern Windows machine from XP onward.

<original.xml repl "[\s]*<ModItem>([\s\S](?!</ModItem>))*<Name>294620323.sbm</Name>[\s\S]*?</ModItem>" "" m >new.xml
Community
  • 1
  • 1
dbenham
  • 127,446
  • 28
  • 251
  • 390