Share via


Read and parse a folder of xml files

Question

Tuesday, May 22, 2012 5:36 PM

We send a bunch of system-generated xml files to a customer.  We need to start providing the customer a manifest of these xmls.  I need to be able to pull out last name and first name from each xml file in a folder to create this one manifest.  It can be xml, xlsx, or csv.  That doesn't matter much as long as the other people can open it.  How would I start this with PowerShell?  So far I have only seen references to reading one xml with a ton of the same fields repeated, not a ton of xml files with unique values in each field only.

All replies (4)

Thursday, May 24, 2012 7:25 AM ✅Answered

Assuming your XML files are similar to this…

<?xml version="1.0" standalone="yes"?>
<Company>
  <Department>
    <ID>0078437</ID>
    <FirstName>Jane</FirstName>
    <LastName>Doe</LastName>
    <SecurityLevel>High</SecurityLevel>
  </Department>
</Company>

…the following code should achieve what you require. Remember, the corresponding highlighted node names in the sample XML file and in the code are case sensitive:

# adapt these two variables to suit your conditions
$dir = 'C:\sandbox'
$manifest = 'C:\Manifest_' + (Get-Date -Format yyyyMMdd) + '.csv'

# process the XML files
Get-ChildItem -Path $dir -Filter *xml | ForEach-Object {

  # retrieve relevant values
  $firstName = Select-Xml -XPath '//FirstName' -Path $_.FullName -ErrorAction SilentlyContinue
  $lastName = Select-Xml -XPath '//LastName' -Path $_.FullName -ErrorAction SilentlyContinue

  # if values were retrieved succesfully
  if ($firstName -and $lastName) {

    # create a custom PSObject and set the values to corresponding properties
    New-Object PSObject -Property @{
      FirstName = $firstName.Node.InnerText
      LastName = $lastName.Node.InnerText
    }
  }
  
  # clear values
  Clear-Variable firstName, lastName
  
    # export custom object to the CSV manifest
} | Export-Csv -Path $manifest -NoTypeInformation -Verbose

Wednesday, May 23, 2012 1:46 AM

If you provide some samples we could provide better advice, but you could structure your code like this:

Get-ChildItem -Filter *.xml | ForEach-Object {$xml = Import-Clixml $_; if ($xml.<something> -eq 'blah') {<do something> } }

There are also these types of articles:

Mike Crowley | MVP
My Blog -- Planet Technologies


Thursday, May 24, 2012 9:28 AM | 1 vote

Hi MadWhiteHatter,

Please feel free to let us know if the information was helpful to you.

Regards,

Tiger Li

TechNet Subscriber Support in forum
If you have any feedback on our support, please contact  [email protected].

Tiger Li

TechNet Community Support


Thursday, May 24, 2012 3:47 PM

I really appreciate both of you.  Tiger Li, you gave me a 90% or better solution.  I just need to change the folders for the most part.  Thank you so much.