Skip to content

Instantly share code, notes, and snippets.

@benthepoet
Created March 14, 2019 01:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benthepoet/f2cba45fd6e8401d76a21bcb91bd8604 to your computer and use it in GitHub Desktop.
Save benthepoet/f2cba45fd6e8401d76a21bcb91bd8604 to your computer and use it in GitHub Desktop.
Parsing XML to CSV
Add-Type -AssemblyName System.Xml.Linq
$reader = [System.Xml.XmlReader]::Create("./magnified.xml")
$reader.ReadStartElement("response")
$reader.ReadStartElement("row")
$csv = @()
while(!$reader.EOF) {
if ($reader.IsStartElement() -and $reader.Name -eq "row") {
$element = [System.Xml.Linq.XElement]::ReadFrom($reader)
if ($null -ne $element) {
$csv += [PSCustomObject]@{
ZipCode = $element.Element("zip_code").Value
TotalPopulation = $element.Element("total_population").Value
MedianAge = $element.Element("median_age").Value
TotalMales = $element.Element("total_males").Value
TotalFemales = $element.Element("total_females").Value
TotalHouseholds = $element.Element("total_households").Value
AverageHouseholdSize = $element.Element("average_household_size").Value
}
}
} else {
$reader.Read() | Out-Null
}
}
$csv | Export-Csv -Path ./Out.csv -NoTypeInformation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment