Evyatar
Evyatar

Reputation: 1157

Change XML Attribute By bat file

I have the following XML File:

<MyXML myatt="true">
   <MyElement>Test</MyElement>
</MyXML>

I want to change the attirbute myatt by .bat file
How can i do it with PowerShell?
Thanks!

Upvotes: 1

Views: 1757

Answers (2)

Magoo
Magoo

Reputation: 79983

@ECHO Off
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "destdir=U:\destdir"
SET "filename1=%sourcedir%\q35534146.txt"
SET "outfile=%destdir%\outfile.txt"

SET "tag=%1"
SET "attribute=%2"
SET "value=%~3"
IF NOT DEFINED value ECHO(Required tag, attribute, "value"&GOTO :EOF 

(
FOR /f "usebackqdelims=" %%a IN ("%filename1%") DO (
 FOR /f "tokens=1,2delims=<=> " %%c IN ("%%a") DO (
  SET "changed="
  IF /i "%%c"=="%tag%" IF "%%d"=="%attribute%" SET "changed=y"&ECHO(^<%%c %attribute%="%value%"^>
  IF NOT DEFINED changed ECHO(%%a
 )
)
)>"%outfile%"

GOTO :EOF

You would need to change the settings of sourcedir and destdir to suit your circumstances.

I used a file named q35534146.txt containing your data for my testing.

Produces the file defined as %outfile%

It is not important that the filenames I used were .txt, replace with .xml as required.

Note that this merely replaces any line beginning

delimiterstagdelimitersattributedelimitersanything

with

<tag attribute="value">

Run as

thisbatch tag attribute "value required"

where the quotes are only required if the value contains separators like spaces.

Upvotes: 0

Evyatar
Evyatar

Reputation: 1157

I think i found the solution but i dont think its the best solution

<# : 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
$nodes = $xml.SelectNodes('MyXML')
foreach($node in $nodes)
{
     node.SetAttribute('myatt','false')
}
$xml.Save($env:xmlfile)

Upvotes: 2

Related Questions