user2731629
user2731629

Reputation:

Add a XML element in the middle of the XML document

I am writing PowerShell script to modify the XML file. I need to add a new element and add attributes to it. I tried using CreateElement() and AppendChild() methods but it doesnt help. Below is my sample input XML file

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Subnet xmlns="http://google.com">
  <Id>Network_106</Id>
  <Name>Network_106</Name>
  <Description>
  </Description>
  <NetworkAddress>173.24.106.0</NetworkAddress>
  <NetworkMask>255.255.255.0</NetworkMask>
</Subnet>

I need to add the new elemetnt called DeliveryServices after a Description like below and add Id element inside it.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Subnet xmlns="http://google.com">
  <Id>Network_106</Id>
  <Name>Network_106</Name>
  <Description>
  </Description>
<DeleveryServices>
  <Id>172.22.22.22</Id>
</DeleveryServices>
  <NetworkAddress>173.24.106.0</NetworkAddress>
  <NetworkMask>255.255.255.0</NetworkMask>
</Subnet>

I tried the below code, but it doesnt work.

[xml]$xdoc = Get-Content "F:\Sample.xml"
$child = $xdoc.CreateElement("DeleveryServices")
$xdoc.Subnet.AppendChild($child)
$xdoc.Subnet.DeleveryServices.Id = "172.22.22.22"

I am getting this below error. And also DeleveryServices element is created at the end of the XML file. I want it after the description.

The property 'Id' cannot be found on this object. Verify that the property
exists and can be set.
At line:44 char:17
+                 $xdoc.Subnet.DeleveryServices.Id = "172.22.22.22"

Upvotes: 1

Views: 7674

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200453

You create a node <DeleveryService>, but that creates just an empty node. It doesn't magically create, add, or populate a child node <Id>. You need to do that yourself:

[xml]$xdoc = Get-Content "F:\Sample.xml"
$child = $xdoc.CreateElement("DeleveryServices")

$id = $xdoc.CreateElement("Id")
$id.InnerText = '172.22.22.22'
$child.AppendChild($id)

$xdoc.Subnet.AppendChild($child)

To add the new node after a particular other node you need to use InsertAfter() instead of AppendChild(), which obviously places the node at the end ("append").

$nsm = New-Object Xml.XmlNamespaceManager($xdoc.NameTable)
$nsm.AddNamespace('ns', $xdoc.DocumentElement.NamespaceURI)

$descr = $xdoc.SelectSingleNode('//ns:Description', $nsm)

$xdoc.Subnet.InsertAfter($child, $descr)

Beware that you need a namespace manager for selecting the Description node, because your XML data uses a namespace.

Upvotes: 1

Jim Garrison
Jim Garrison

Reputation: 86774

$child = $xdoc.CreateElement("DeleveryServices")
                              ^^^^^^^^^^^^^^^^
$xdoc.Subnet.AppendChild($child)
$xdoc.Subnet.DeliveryServices.Id = "172.22.22.22"
             ^^^^^^^^^^^^^^^^

Note that DeleveryServices != DeliveryServices

Upvotes: 1

Related Questions