Friday, August 10, 2012

XML-PowerShell creating new child elements and attributes

Scenario: How to create new XML elements, attributes and write to a new/existing XML file using PowerShell


$OutputXML = New-Object xml;

            [System.Xml.XmlDeclaration] $xmlDeclaration = $OutputXML.CreateXmlDeclaration("1.0", "UTF-16", $null);

            $OutputXML.AppendChild($xmlDeclaration) | Out-Null;

             #creates root element named Book

            $BookElement = $OutputXML.CreateElement("Book"); 

            $BookElement.SetAttribute("BookName", "Monk_Who_Sold_His_Ferrari");   

                  $OutputXML.AppendChild($BookElement) | Out-Null;

                  #creates and adds Author element as child element to Book

                  $AuthorElement = $OutputXML.CreateElement("Author"); 

                  $AuthorElement.InnerText = "Robin S Sharma";

                  $BookElement.AppendChild($AuthorElement)| Out-Null;

                  #Checks if the XML file exists else create a new XML file

                  $XMLFilePath = "c:\srini.xml"

                   if (-not (Test-Path $XMLFilePath))


                     New-Item $XMLFilePath  -Type File  | Out-Null;


<?xml version="1.0" encoding="UTF-16"?>
<Book BookName="Monk_Who_Sold_His_Ferrari">
  <Author>Robin S Sharma</Author>