Reputation: 3511
I have this xml file where i want to add the "<Department>Sales</Department>"
to every person tag. I want to add this using powershell and keep the format. any pointers will be helpful
Before :
<employees>
<person>
<name>John</name>
<Age>36</Age>
</person>
<person>
<name>Jack</name>
<Age>38</Age>
</person>
<person>
<name>Jill</name>
<Age>34</Age>
</person>
</employees>
After:
<employees>
<person>
<name>John</name>
<Age>36</Age>
<Department>Sales</Department>
</person>
<person>
<name>Jack</name>
<Age>38</Age>
<Department>Sales</Department>
</person>
<person>
<name>Jill</name>
<Age>34</Age>
<Department>Sales</Department>
</person>
</employees>
Upvotes: 0
Views: 21
Reputation: 61168
The example xml is missing a root tag, so if I add that:
[xml]$xml = @'
<root>
<employees>
<person>
<name>John</name>
<Age>36</Age>
</person>
<person>
<name>Jack</name>
<Age>38</Age>
</person>
<person>
<name>Jill</name>
<Age>34</Age>
</person>
</employees>
</root>
'@
You can loop through the employees->person nodes and append a new node to each of them:
$xml.DocumentElement.employees.person | ForEach-Object {
$newTag = $xml.CreateElement('Department')
$newTag.InnerText = 'Sales'
$_.AppendChild($newTag)
}
Output:
<root>
<employees>
<person>
<name>John</name>
<Age>36</Age>
<Department>Sales</Department>
</person>
<person>
<name>Jack</name>
<Age>38</Age>
<Department>Sales</Department>
</person>
<person>
<name>Jill</name>
<Age>34</Age>
<Department>Sales</Department>
</person>
</employees>
</root>
Upvotes: 1