How to add an attribute to the XML file using Powershell?

To add the attribute to the XML, we first need to add the Element and then we will add an attribute for it.

Below is a sample of the XML file.


<?xml version="1.0"?>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <description>An in-depth look at creating applications with XML.</description>

The below command will add the new element but the file won’t be saved. We will save the file after the attribute is added.

$file = "C:\Temp\SampleXML.xml"
$xmlfile = [xml](Get-Content $file)
$newbookelement = $xmlfile.CreateElement("book")
$newbookelementadd = $xmlfile.catalog.AppendChild($newbookelement)

To insert the attribute and save the file,

$newbookattribute = $newbookelementadd.SetAttribute("id","bk001")


To add the nested elements or if we need to add the attributes under the newly created node use the below code,


$file = "C:\Temp\SampleXML.xml"
$xmlfile = [XML](Get-Content $file)
$newbooknode = $xmlfile.catalog.AppendChild($xmlfile.CreateElement("book"))
$newauthorelement = $newbooknode.AppendChild($xmlfile.CreateElement("author"))
$newauthorelement.AppendChild($xmlfile.CreateTextNode("Jimmy Welson")) | Out-Null
$newtitleelement = $newbooknode.AppendChild($xmlfile.CreateElement("title"))
$newtitleelement.AppendChild($xmlfile.CreateTextNode("PowerShell One")) | OutNull