Loop through nodes and change tree structure xml

Viewed 42

I am trying to change an xml file from one structure to the other using only a few things that I need using powershell. The source file looks like this:

<?xml version="1.0" encoding="iso-8859-1"?>
<Files xmlns="http://testnamespace.com">
  <File>
    <Naam>filenameone.XML</Naam>
    <Type>testtype</Type>
    <Lines>15</Lines>
  </File>
  <File>
    <Name>filenametwo.XML</Name>
    <Type>Journaalposten</Type>
    <Lines>3</Lines>
  </File>
  <Amount>0,00</Amount>
  <Indication>D</Indication>
</Files>

And the idea is to transform it into this:

<?xml version="1.0" encoding="iso-8859-1"?>
<Files xmlns="http://testnamespace.com">
  <File>filenameone.XML</File>
  <File>filenametwo.XML</File>
</Files>

I currently have everything in place to pick up the file and all that, I'm just looking to change the xml structure and save the file. I don't know if it's better to write a whole new file or to loop through the elements and change them as I go this is what I currently have:

$transportFile = Get-ChildItem -Path $currentLocation -Filter *transport*
[xml]$xml = Get-Content -Path $transportFile
$nsm = New-Object Xml.XmlNamespaceManager($xml.NameTable)
$nsm.AddNamespace('ns', $xml.DocumentElement.NamespaceURI)
$ParametersNode = $xml.SelectNodes('//ns:Files', $nsm)

foreach($Node in $ParametersNode){
   #Do something to transform the current node
}
$xml.Save('test.xml')
1 Answers

I would suggest you do it another way.

Create a new blank file, search for the target information in the old file and append it to the new. Something like this:

$oldfile = [xml]'[[[your xml above]]]'

$newfile = [xml]'<?xml version="1.0" encoding="iso-8859-1"?>
<Files xmlns="http://testnamespace.com">  
</Files>'

$targets = $oldfile.SelectNodes("//*[local-name()='Files']/*[local-name()='File']/*[local-name()='Name']/text()").InnerText 

foreach ($target in $targets)    
{  
  $entry = $newfile.CreateElement("File","http://testnamespace.com")  
  $entry.InnerText=$target
  $newfile.Files.AppendChild($entry) 
}
echo $newfile.OuterXml

Output (sorry about the formatting, but that can be fixed later):

<?xml version="1.0" encoding="iso-8859-1"?>
<Files xmlns="http://testnamespace.com">
<File>filenameone.XML</File><File>filenametwo.XML</File>
</Files>
Related