2

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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

I knew Attributes had to be there somewhere, I just was putting it into the ForEach. Beautiful, Thanks for the -RAW info as well. Thank you!!!
What is a DOM.?
@AbrahamZinala, it is short for Document Object Model

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.