+ Reply to Thread
Results 1 to 2 of 2

Thread: inserting multiple XML elements

  1. #1
    Junior Member
    Join Date
    Apr 2012
    Posts
    34

    inserting multiple XML elements

    I have an XML structure similar to that :
    Code:
    <a>
      <b>
        <c>aa</c>
      </b>
      <d>
        <e>bb</e>
      </d>
    </a>
    I need to insert more elements inside the <d> to be like that
    Code:
    <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:
    Code:
    $xml = "file.xml"
    $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.

  2. #2
    Junior Member
    Join Date
    May 2012
    Posts
    36
    You should use the CreateElement method on the XmlDocument instance e.g.:
    Code:
    $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:
    Code:
    $xml = [xml](Get-Content path_to_xml_file)

+ Reply to Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts