Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a new row on XML file

I have an XML file.
I want to add a new row to the XML with a batch script.

An example of the xml file is:

<MyXML flag="0">
     <MyRow Path="C:\a.txt" DisplayName="a"/> 
     <MyRow Path="C:\b.txt" DisplayName="b"/> 
</MyXML>


After run the batch file:
:

 <MyXML flag="0">
     <MyRow Path="C:\a.txt" DisplayName="a"/> 
     <MyRow Path="C:\b.txt" DisplayName="b"/> 
     <MyRow Path="C:\c.txt" DisplayName="c"/> 
</MyXML>

How can i do it with batch script?


2 Answers

It's better to parse XML as XML, rather than as predictably formatted flat text to hack and scrape. Here's a very basic batch + PowerShell hybrid script that'll demonstrate exactly what you asked for.

<# : batch portion
@echo off
setlocal

set "xmlfile=test.xml"

powershell -noprofile "iex (${%~f0} | out-string)"
goto :EOF

: end batch / begin PowerShell #>

[xml]$xml = gc $env:xmlfile
$add = $xml.createElement('MyRow')
$add.setAttribute('Path', 'C:\c.txt')
$add.setAttribute('DisplayName', 'c')
$xml.MyXML.appendChild($add)
$xml.Save($env:xmlfile)

... Or if you prefer a batch + JScript hybrid:

@if (@CodeSection == @Batch) @then
@echo off
setlocal

set "xmlfile=test.xml"

cscript /nologo /e:JScript "%~f0" "%xmlfile%"
goto :EOF

@end // end batch / begin JScript

var xml = WSH.CreateObject('MSXML2.DOMDocument.6.0');
xml.load(WSH.Arguments(0));
var add = xml.createElement('MyRow');
add.setAttribute('Path', 'C:\\c.txt');
add.setAttribute('DisplayName', 'c');
xml.selectSingleNode('//MyXML[@flag=0]').appendChild(add);
xml.save(WSH.Arguments(0));
like image 180
rojo Avatar answered Jan 21 '26 01:01

rojo


with replacer.bat:

call replacer.bat "e?xml.txt" "</MyXML>" "\t<MyRow Path=\u0022C:\\c.txt\u0022 DisplayName=\u0022c\u0022/>\r\n</MyXML>"

e? is for evaluation of special characters like new lines,tabs and so on.Qor quotes unicode escapes are used. Though with such jscript/batch hybrids is possible to use xml parsers I have no ready to use scripts.

like image 41
npocmaka Avatar answered Jan 21 '26 02:01

npocmaka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!