I have an XML file that has multiple nodes, but not every child node is in every node (Not 100% I am using that terminology correctly). I need to export the child nodes into a CSV as column headers. If the child node is missing from the first node, than that childnode is not included as a header and the data is not pulled.
Example:
<data>
<row>
<TEST_REF_ID>10001001</TEST_REF_ID>
<TEST_FIRST_NAME>Samuel</TEST_FIRST_NAME>
<TEST_LAST_NAME>Adams</TEST_LAST_NAME>
<TEST_SEX>M</TEST_SEX>
<TEST_BIRTHDATE>01/01/2001</TEST_BIRTHDATE>
</row>
<row>
<TEST_REF_ID>20002002</TEST_REF_ID>
<TEST_FIRST_NAME>John</TEST_FIRST_NAME>
<TEST_MIDDLE_NAME>R</TEST_MIDDLE_NAME>
<TEST_LAST_NAME>Smith</TEST_LAST_NAME>
<TEST_SEX>M</TEST_SEX>
<TEST_BIRTHDATE>01/01/1999</TEST_BIRTHDATE>
<TEST_SSN>123456789</TEST_SSN>
</row>
</data>
If I do this:
#Location of XML Data is in a URL
[xml]$export = Invoke-WebRequest -Uri $url -Credential $credential
$export.data.row | Export-Csv "C:\test.csv" -NoTypeInformation
Columns TEST_MIDDLE_NAME and TEST_SSN would not be included in the CSV.
If I do this:
$columns = 'TEST_REF_ID', 'TEST_FIRST_NAME', 'TEST_MIDDLE_NAME',
'TEST_LAST_NAME', 'TEST_SEX', 'TEST_BIRTHDATE', 'TEST_SNN'
[xml]$export = Invoke-WebRequest -Uri $url -Credential $credential
$export.data.row |
Select-Object $columns |
Export-Csv "C:\test.csv" -NoTypeInformation
all the columns are included as long as I know what they are before hand. If the column name changes, then it will not be included and the column I have incorrect will just have no data.
If I do this:
#Location of XML Data is in a URL
[xml]$export = Invoke-WebRequest -Uri $url -Credential $credential
$export.SelectNodes("data/row/*") | Select-Object -Expand Name -Unique
It will give me all the column names, which I could use as the headers, but it does not give them to me in the correct order. It gives them back in the order they are retrieved, so in this case it would return: TEST_REF_ID, TEST_FIRST_NAME, TEST_LAST_NAME, TEST_SEX, TEST_BIRTHDATE, TEST_MIDDLE_NAME, TEST_SNN.
It brings back the first set in a row, then adds on the two that were missing front the first set on to the end of the list. I need them to be pulled back in the correct order as displayed in the nodes.
I hope that all makes sense, using the $Column
method does do it exactly what I need, but it breaks if changes are made with out my knowledge, I am hoping to remedy that possibility if possible.