Home > OS >  im getting problems while converting xml to csv using powershell
im getting problems while converting xml to csv using powershell

Time:01-27

My xml looks like:

<Line>
  <Item>3820-2013-00</Item> 
  <Type>SpecTdp Revision</Type> 
  <Rev>B</Rev> 
  <Name>BLACK KAL-GARD SCREW</Name> 
  <owning_site /> 
  <Commodity>HO Hardware</Commodity> 
  <Family>HW-MEC Mech Part</Family> 
  <Security>Un Classified</Security> 
  <Status>Released</Status> 
  <ActionCode /> 
  <LogisticAlert /> 
  <MediaType>DI-MEDIA</MediaType> 
  <CompanyData>DD</CompanyData> 
  <EdnEng_Dwg /> 
  <Eco>D35882/00</Eco> 
  <Project /> 
  <plmpdf>un3820-2013-00#RevB#A0#S2.pdf</plmpdf> 
  <plmpdf_Link>un3820-2013-00#RevB#A0#S2.pdf</plmpdf_Link> 
  <change_plmpdf>unD35882#Rev00#A0#S1.pdf</change_plmpdf> 
  <change_plmpdf_Link>unD35882#Rev00#A0#S1.pdf</change_plmpdf_Link> 
  <ProdFiles>
    <prod>un3820-2013-00RevB.x_t</prod> 
    <prod>un3820-2013-00RevB.zip</prod> 
  </ProdFiles>
</Line>

I would like to get 2 rows in the CSV file for each <prodfiles> value.
When I'm doing:

$inputFile.Line.ChildNodes  | Export-Csv "$b" -NoTypeInformation -Delimiter:";" -Encoding:UTF8

I get xml.object for the value of prodfiles.

CodePudding user response:

One possible way is to insert a ForEach-Object that "unrolls" the ProdFiles elements, then pipes the output to Export-Csv:

$inputFile.Line.ChildNodes | ForEach-Object {
    if( $_.Name -eq 'ProdFiles' ) { 
        $_.ChildNodes  # Output the child nodes of the current node
    } else { 
        $_             # Forward the current node as-is
    }
} | Export-Csv "$b" -NoTypeInformation -Delimiter ";" -Encoding UTF8

With PS 7.x you could use ternary operator to create more succinct code:

$inputFile.Line.ChildNodes | ForEach-Object {
    $_.Name -eq 'ProdFiles' ? $_.ChildNodes : $_
} | Export-Csv "$b" -NoTypeInformation -Delimiter ";" -Encoding UTF8
  •  Tags:  
  • Related