Reading XML with PowerShell

    Reading XML with PowerShell

    PowerShell provides built-in support for working with XML data. You can easily create, parse, query, and modify XML documents using cmdlets and the .NET Framework's XmlDocument and XmlElement classes.

    We can read XML files using PowerShell. For example, we have the following content in foods.xml file

     
    <?xml version="1.0" encoding="utf-8"?>
    <foods>
    	<food>
    		<name>Belgian Waffles</name>
    		<price>$5.95</price>
    		<description>Two of our famous Belgian Waffles with plenty of real maple syrup</description>
    		<calories>650</calories>
    	</food>
    	<food>
    		<name>Strawberry Belgian Waffles</name>
    		<price>$7.95</price>
    		<description>Light Belgian waffles covered with strawberries and whipped cream</description>
    		<calories>900</calories>
    	</food>
    	<food>
    		<name>Berry-Berry Belgian Waffles</name>
    		<price>$8.95</price>
    		<description>Light Belgian waffles covered with an assortment of fresh berries and whipped cream</description>
    		<calories>900</calories>
    	</food>
    	<food>
    		<name>French Toast</name>
    		<price>$4.50</price>
    		<description>Thick slices made from our homemade sourdough bread</description>
    		<calories>600</calories>
    	</food>
    	<food>
    		<name>Homestyle Breakfast</name>
    		<price>$6.95</price>
    		<description>Two eggs, bacon or sausage, toast, and our ever-popular hash browns</description>
    		<calories>950</calories>
    	</food>
    </foods>

    Read the xml document

     
    PS C:\Temp> [xml]$XmlDocument = Get-Content .\foods.xml
    PS C:\Temp> $XmlDocument
    
    xml                            foods
    ---                            -----
    version="1.0" encoding="utf-8" foods
    
    PS C:\Temp> $XmlDocument.foods
    
    food
    ----
    {Belgian Waffles, Strawberry Belgian Waffles, Berry-Berry Belgian Waffles, French Toast...}
    
    PS C:\Temp> $XmlDocument.foods.food
    
    name                        price description                                                                         calories
    ----                        ----- -----------                                                                         --------
    Belgian Waffles             $5.95 Two of our famous Belgian Waffles with plenty of real maple syrup                   650
    Strawberry Belgian Waffles  $7.95 Light Belgian waffles covered with strawberries and whipped cream                   900
    Berry-Berry Belgian Waffles $8.95 Light Belgian waffles covered with an assortment of fresh berries and whipped cream 900
    French Toast                $4.50 Thick slices made from our homemade sourdough bread                                 600
    Homestyle Breakfast         $6.95 Two eggs, bacon or sausage, toast, and our ever-popular hash browns                 950
    
    PS C:\Temp> $XmlDocument.foods.food.name
    Belgian Waffles
    Strawberry Belgian Waffles
    Berry-Berry Belgian Waffles
    French Toast
    Homestyle Breakfast
     
     
     

    We can also use Select-Xml cmdlet to directly read the values.

     
    PS C:\Temp> $path = .\foods.xml
    PS C:\Temp> $path = ".\foods.xml"
    PS C:\Temp> $xpath = "/foods/food"
    PS C:\Temp> Select-Xml -Path $path -XPath $xpath | Select-Object -ExpandProperty Node
    
    name                        price description                                                                         calories
    ----                        ----- -----------                                                                         --------
    Belgian Waffles             $5.95 Two of our famous Belgian Waffles with plenty of real maple syrup                   650
    Strawberry Belgian Waffles  $7.95 Light Belgian waffles covered with strawberries and whipped cream                   900
    Berry-Berry Belgian Waffles $8.95 Light Belgian waffles covered with an assortment of fresh berries and whipped cream 900
    French Toast                $4.50 Thick slices made from our homemade sourdough bread                                 600
    Homestyle Breakfast         $6.95 Two eggs, bacon or sausage, toast, and our ever-popular hash browns                 950

     

    Here are some examples of common XML operations in PowerShell:

    Create an XML document:

    # Create a new XmlDocument
    $xmlDoc = New-Object System.Xml.XmlDocument
    
    # Create a root element
    $root = $xmlDoc.CreateElement("root")
    $xmlDoc.AppendChild($root)
    
    # Create a child element
    $child = $xmlDoc.CreateElement("child")
    $child.InnerText = "Hello, world!"
    $root.AppendChild($child)
    
    # Save the XML document to a file
    $xmlDoc.Save("output.xml")
    

     

    Load an XML document from a file:

    # Load the XML document
    $xmlDoc = New-Object System.Xml.XmlDocument
    $xmlDoc.Load("input.xml")
    

     

    Load an XML document from a string:

    $xmlString = @"
    <root>
      <child>Hello, world!</child>
    </root>
    "@
    
    # Load the XML document
    $xmlDoc = New-Object System.Xml.XmlDocument
    $xmlDoc.LoadXml($xmlString)
    

     

    Query an XML document using XPath:

    # Load the XML document
    $xmlDoc = New-Object System.Xml.XmlDocument
    $xmlDoc.Load("input.xml")
    
    # Select nodes using XPath
    $childNodes = $xmlDoc.SelectNodes("/root/child")
    
    # Iterate over the selected nodes
    foreach ($child in $childNodes) {
        Write-Host $child.InnerText
    }
    

     

    Modify an XML document:

    # Load the XML document
    $xmlDoc = New-Object System.Xml.XmlDocument
    $xmlDoc.Load("input.xml")
    
    # Select a node using XPath
    $childNode = $xmlDoc.SelectSingleNode("/root/child")
    
    # Modify the node's content
    $childNode.InnerText = "New content"
    
    # Save the modified XML document to a file
    $xmlDoc.Save("output.xml")
    

     

    Remove an element from an XML document:

    # Load the XML document
    $xmlDoc = New-Object System.Xml.XmlDocument
    $xmlDoc.Load("input.xml")
    
    # Select a node using XPath
    $childNode = $xmlDoc.SelectSingleNode("/root/child")
    
    # Remove the node
    $childNode.ParentNode.RemoveChild($childNode)
    
    # Save the modified XML document to a file
    $xmlDoc.Save("output.xml")
    

     

    These examples demonstrate the basic operations you can perform on XML documents using PowerShell. You can combine and extend these examples to create more complex XML processing scripts.