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"?>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <description>An in-depth look at creating applications with XML.</description>

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.


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


You can check the new book element is created.

Published on 19-Feb-2021 17:46:50