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?

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.