Home > OS >  How to use Powershell to enumerate attributes of an XML element
How to use Powershell to enumerate attributes of an XML element

Time:11-06

I have an XML file that is structured like this:

<XMLFile>
    <Thing Stuff1='data' Stuff2='data' Stuff3='data' .....Stuff100='data'</Thing>
    <Thing Stuff1='data' Stuff2='data' Stuff3='data' .....Stuff85='data'</Thing>
    <Thing Stuff1='data' Stuff2='data' Stuff3='data' .....Stuff91='data'</Thing>
    .
    .
    .
</XMLFile>

The attributes in each Thing are not always the same, some may be present and some may not. I read the file into $xmldata like this:

[xml]$xmldata = Get-Content -Path xmlfilename

I access each 'Thing' in $xmldata like this:

$xmldata.XMLFile.Thing

I want to enumerate all the Stuff attributes using something like

$xmldata.XMLFile.Thing.ForEach({$_.??????})

What do I use in place of the question marks to get a list of all the 'Stuff' items in each 'Thing'?

CodePudding user response:

# Parse the XML file into a DOM.
[xml] $xmldata = Get-Content -Raw -LiteralPath xmlfilename

# Loop over the 'Thing' elements' attributes and emit them as 
# custom objects with names and values.
$xmlData.XMLFile.Thing.Attributes.ForEach({ 
  [pscustomobject] @{ Name = $_.Name; Value = $_.Value }
})

Note the use of -Raw to speed up parsing the input file into an XML DOM. However, the robust way to parse an XML file that avoids character-encoding pitfalls requires the technique described in the bottom section of this answer.

  • Related