How to add a new element in the XML using PowerShell?

PowerShellMicrosoft TechnologiesSoftware & Coding

Suppose we have a XML file as shown below.

<?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>

We need to add a new node. So we will first load the XML file and then operate on it as shown below.

The below command will save the XML file to the variable.

$xmlfile = [XML](Get-Content C:\Temp\SampleXML.xml)

The below command will create a new XML element

$newelement = $xmlfile.CreateElement("book")

Once the element is created we need to append it to the specific node. Here we need to append a new element underneath the Catalog.

$xmlfile.catalog.AppendChild($newelement)

And the last part is to save the XML file using the below command.

$xmlfile.save('C:\Temp\SampleXML.xml')

You can check the new book element is created.

raja
Published on 19-Feb-2021 13:16:50
Advertisements