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.

Example

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications with XML.</description>
   </book>
</catalog>

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")
$xmlfile.Save($file)

Output

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

Example

$file = "C:\Temp\SampleXML.xml"
$xmlfile = [XML](Get-Content $file)
$newbooknode = $xmlfile.catalog.AppendChild($xmlfile.CreateElement("book"))
$newbooknode.SetAttribute("id","bk102")
$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
$xmlfile.save($file)

Output

Updated on: 01-Mar-2021

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements