xml - Adding and Removing Xmlnode using Powershell -
i trying add , remove elements multiple xml files. ran 2 issue. removed empty elements automatically , second did not remove wanted to
i have xml 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 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 , removed itemtoremove on output xml above.
with current script have used <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 removed not want happen, newitemtoadd added good, , itemtoremove node not removed not want
here 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) }
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 }
Comments
Post a Comment