简体   繁体   中英

How to use Powershell to enumerate attributes of an XML element

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'?

# 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM