Sunday, October 13, 2019

Converting XML to CSV


Better coding through PowerShell
$DataIn=New-Object System.Xml.XmlDocument
#Set starting point
$InFilePath=“F:\Query_Results\Complete\XML\X_to_Z”
#Set CSV Output Location
$OutFIlePath=“F:\Query_Results\Complete\1CSVs”
#Look through starting point for sub directories
Get-ChildItem -Directory -Path “$InFilePath” | ForEach-Object {
   #set subdirectory Path
   $SubDirectory=$_.FullName
   #Set Output CSV file
   $FileName=$_
   $OutFile=“$OutFilePath"+”$FileName"+“.csv”
   #monitor Progress
   Write-Host $OutFile
   #Get Contents of Sub Directory
   Get-ChildItem $SubDirectory | ForEach-Object {
      #Get Files to read
      $InFile = $_.FullName
      #DEBUG
      #Write-Host $InFile
      #Load Data
      $DataIn.Load(“$InFile”)
      #Check for data
      If($DataIn.Response.Count -ne 0){
        #parse content
        $Header=$DataIn.Response.SearchCriteria
        $IndexofMake=$Header.LastIndexOf(’ | ’)
        $ModelYear=($Header.Substring($IndexofMake+13,4) -replace “,”, “,”)
        $Body = $DataIn.Response.Results.MakeModels
        $Body | ForEach-Object{
          #set data to output
          $Make=($_.Make_Name -replace “,”, “,”)
          $MakeID=($_.Make_ID -replace “,”, “,”)
          $ModelID=($_.Model_ID -replace “,”, “,”)
          $ModelName=($_.Model_Name -replace “,”, “,”)
          $OutData = $ModelYear+ “,” + $Make + “,” + $MakeID + “,” + $ModelName + “,” + $ModelID
          #DEBUG
          #Write-Host “$OutData”
          #save data to file

          Add-Content -Path “$OutFile” -Value “$OutData” -Encoding UTF8
        }
     }
  }
} 

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.