- 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
Advertisements
To Continue Learning Please Login
Login with Google