Adding and Removing Xmlnode using Powershell

Justin Homes picture Justin Homes · May 29, 2014 · Viewed 32.3k times · Source

I am trying to add and remove elements from multiple xml files. i ran into two issue. it removed empty elements automatically and second it did not remove what i wanted to

I have my xml like this

<Entity>
   <App>
      <item1>1</item1>
      <emptyItem/>
      <person>
         <itemToRemove>true</itemToRemove>
         <emptyItem/>
         <otheritem>1</otheritem>
      </person>
      <person>
         <itemToRemove>false</itemToRemove>
         <emptyItem/>
         <otheritem>3</otheritem>
      </person>
      <person>
         <itemToRemove>false</itemToRemove>
         <emptyItem/>
         <otheritem>3</otheritem>
      </person>
   </App>
</Entity>

what i want is

<Entity>
   <App>
      <item1>1</item1>
      <emptyItem/>
      <person>

         <emptyItem/>
         <otheritem>1</otheritem>
      </person>
      <person>

         <emptyItem/>
         <otheritem>3</otheritem>
      </person>
      <person>

         <emptyItem/>
         <otheritem>3</otheritem>
      </person>
      <newItemtoAdd>2001-01-01</newItemtoAdd>
   </App>
</Entity>

i added newItemtoAdd element and removed itemToRemove on output xml above.

with the current script i have used what i get is this

<Entity>
   <App>
      <item1>1</item1>
      <emptyItem/>
      <person>
         <itemToRemove>true</itemToRemove>
         <otheritem>1</otheritem>
      </person>
      <person>
         <itemToRemove>false</itemToRemove>
         <otheritem>3</otheritem>
      </person>
      <person>
         <itemToRemove>false</itemToRemove>
         <otheritem>3</otheritem>
      </person>
      <newItemtoAdd>2001-01-01</newItemtoAdd>
   </App>
</Entity>

emptyItem node is removed which i do not want to happen, newItemtoAdd is added which is good, and itemToRemove node is not removed which is not what i want

here is my script

Get-ChildItem D:\Projects\*.xml | 
    % { 
        [xml]$xml      = [xml](Get-Content $_.fullname)
        $newItemtoAdd = $xml.CreateElement('newItemtoAdd')
        $newItemtoAdd.PsBase.InnerText = '1900-01-01'
        $null     = $xml.Entity.App.AppendChild($newItemtoAdd)

    $xml.SelectNodes("//Entity/App/person") | ? {
    $_.name -eq "itemToRemove"   } | % {$_.ParentNode.RemoveChildNode($_) }
       $xml.Save($_.FullName)
    }

Answer

Alexander Obersht picture Alexander Obersht · May 31, 2014
Get-ChildItem D:\Projects\*.xml | % {
    [Xml]$xml = Get-Content $_.FullName

    $newItemtoAdd = $xml.CreateElement('newItemtoAdd')
    $newItemtoAdd.PsBase.InnerText = '1900-01-01'
    $xml.Entity.App.AppendChild($newItemtoAdd) | Out-Null

    $parent_xpath = '/Entity/App/person'
    $nodes = $xml.SelectNodes($parent_xpath)
    $nodes | % {
        $child_node = $_.SelectSingleNode('itemToRemove')
        $_.RemoveChild($child_node) | Out-Null
    }

    $xml.OuterXml | Out-File $_.FullName
}