PowerShell – Ways to Update XML Data

Let’s do a quick overview of the simple XML file. Below diagram should represent the xml structure


Below is the actual XML File

<?xml version="1.0" encoding="UTF-8"?>

<carsdealers>

<car make="GM">

<Gear type="Auto">5</Gear>

<Drivemode>FourWheel</Drivemode>

<year>2015</year>

<price>30000.00</price>

<discount>750.00</discount>

</car>

</carsdealers>

Let’s, Just into PowerShell Scripts. Now, we need to update the Gear type from auto to Manual

Github link to PowerShell –  https://raw.githubusercontent.com/mani0070/Automate/master/XML/UpdateAttribute.ps1

 

 </span>$filePath = 'G:\BlogScripts\cars.xml'
$xml=New-Object XML
$xml.Load($filePath)
$node=$xml.carsdealers.car.Gear
$node.type='Maual'
$xml.Save($filePath)

 

Example 2 :  some other ways of doing it

XML below

 <?xml version="1.0" encoding="UTF-8"?>
<carsdealers>
<car make="GM">
<Gear type="Auto">5</Gear>
<Drivemode>FourWheel</Drivemode>
<year>2015</year>
<price>30000.00</price>
<discount>750.00</discount>
</car>
<car make="Teelsa">
<Gear type="Manual">7</Gear>
<Drivemode>TwoWheel</Drivemode>
<year>2015</year>
<price>25000.00</price>
<discount>750.00</discount>
</car>
</carsdealers>

Method 2 : Using the SelectNodes


$filePath = 'G:\BlogScripts\cars.xml'
$xml=New-Object XML
$xml.Load($filePath)
$nodes = $xml.SelectNodes('/carsdealers/car/Gear');
foreach($node in $nodes)
{
$node.SetAttribute('type', 'Manual');
}
$xml.Save($filePath)

 

Method 3 : Using the Xpath and Get-content


$filePath = 'G:\BlogScripts\cars.xml'
$xml=[XML] (Get-Content $filePath)
$nodes = Select-Xml -Xml $xml -XPath '//@type'
foreach($node in $nodes)
{
$node.Node.Value =$node.Node.Value.Replace('Auto','Manual')
}
$xml.Save($filePath)

 

There may be lot more ways to do, But this can be helpful for any beginner.

 

Hope you enjoyed this article.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.