I decided to implement a XML couple template functions. �Rather than reading the single XML file and using dot notation for every element I created a bunch of XML files to use as templates. �Each XML file represents an individual XML element. �When I need to insert a common XML element into the XML document I'm now just reading the XML template file and replacing what I want. �It's much cleaner.

Let's say I need to insert a new car element here. I could do something like this to create another XML element but it's not only long but it's not real intuitive. It's also a pain when I have to do this over and over again for multiple elements.

[xml]$XmlDoc = Get-Content -Path 'C:\CarDocument.xml'
$xCar = $XmlDoc.CreateElement('Car')
$xCar.SetAttribute('Color', 'Blue')
$xCar.SetAttribute('Type', 'Truck')
$xCarInterior = $XmlDoc.CreateElement('Interior')
$xCar.AppendChild($xCarInterior)
$xCarDash = $XmlDoc.CreateElement('Dashboard')
$xCarDash.InnerText = 'Plastic'
$xCar.SelectSingleNode('Interior').AppendChild($xCarDash)
$XmlDoc.Document.SelectSingleNode('Cars').AppendChild($xCar)
$XmlDoc.Save('C:\CarDocument.xml')

Here's an example of taking an array of cars (hashtables) and by using XML templates I can quickly create as many like-structured XML elements (cars) as I'd like.

[xml]$XmlDoc = Get-Content -Path 'C:\CarDocument.xml'
$NewCarsToAdd = @(
    @{'Color' = 'Yellow'; 'Type' = 'Truck'; 'Dashboard' = 'Suede'} 
    @{'Color' = 'Green'; 'Type' = 'SUV'; 'Dashboard' = 'Wood'}
)
$xCar = [xml](Get-Content C:\Car.xml)
foreach ($Car in $NewCarsToAdd) {
    $xNewCar = $xCar
    $xNewCar.Car.Color = $Car.Color
    $xNewCar.Car.Type = $Car.Type
    $xNewCar.Car.Interior.SelectSingleNode('Dashboard').InnerText = $Car.Dashboard
    $xNewCar = $XmlDoc.ImportNode($xNewCar.SelectSingleNode('Car'),$true) 
    $XmlDoc.SelectSingleNode('Document').AppendChild($xNewCar)
    $XmlDoc.Save('C:\CarDocument.xml')
}

Join the Jar Tippers on Patreon

It takes a lot of time to write detailed blog posts like this one. In a single-income family, this blog is one way I depend on to keep the lights on. I'd be eternally grateful if you could become a Patreon patron today!

Become a Patron!