generalwrex
generalwrex

Reputation: 13

Batch - Removing parent section of a specific child in an XML file

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!)

Upvotes: 1

Views: 108

Answers (2)

dbenham
dbenham

Reputation: 130819

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

Upvotes: 1

Aacini
Aacini

Reputation: 67216

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.

Upvotes: 1

Related Questions