1

I have an XML file with a structure similar to the following:

<a>
  <b>
    <c>aa</c>
  </b>
  <d>
    <e>bb</e>
  </d>
</a>

What I need to do is insert additional elements into , to get something along the lines of:

<a>
  <b>
    <c>aa</c>
  </b>
  <d>
    <e>bb</e>
    <e>cc</e>
    <e>dd</e>
    <e>ff</e>
    <e>gg</e>
  </d>
</a>

I am trying to do this in Powershell. Here is what I tried:

$xml = "path_to_xml_file"
$e1 = $xml.a.d.e
$e2 = $e1.clone()
$e2 = "cc"
$xml.a.d.InsertAfter($e2,$e1)
$xml.save("path_to_xml_file")

But this gives me an error. Could someone suggest how to go about doing this?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Alex
  • 507
  • 1
  • 5
  • 7

1 Answers1

3

You should use the CreateElement method on the XmlDocument instance e.g.:

$xml = [xml]@'
<a>
  <b>
    <c>aa</c>
  </b>
  <d>
    <e>bb</e>
  </d>
</a>
'@

$newNode = $xml.CreateElement('e')
$newNode.InnerText = "cc"
$xml.a.d.AppendChild($newNode) 

Also, if getting XML from a file you should use:

$xml = [xml](Get-Content path_to_xml_file)
Keith Hill
  • 194,368
  • 42
  • 353
  • 369