- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Articles
- How to read the XML file in PowerShell?
- How to add a new element in the XML using PowerShell?
- How to delete the specific node from the XML file using PowerShell?
- How to update the specific node of the XML file using PowerShell?
- How to add the entry in the windows host file using PowerShell?
- How to create animation using XML file in an Android App?
- How to create animation using XML file in an Android App using Kotlin?
- How to convert JSON file to CSV file using PowerShell?
- How to search in the file using PowerShell?
- How to edit the CSV file using PowerShell?
- How to mount the ISO file using PowerShell?
- How to dismount the ISO file using PowerShell?
- How to get the file extension using PowerShell?
- How to install the MSI file using PowerShell?
- How to create Python objects based on an XML file?

Advertisements