Kent Thayer
Kent Thayer

Reputation: 11

Reading an XML File using an XML object results in missing entries

I’ve been given XML files to update, but when reading in the file using an XML object, multiple entries go missing.

The XML File (note two sectionGroup’s)

<configuration>
  <configSections>
    <sectionGroup name="Albert" type="Male, Outlook=neutral" >
         <section name="Bobby" type="Male, Outlook=happy"/>
         <section name="Cathy" type="Female, Outlook=neutral"/>
         <section name="David" type="Male, History=Yes"/>
         <sectionGroup name="Mark" type="Male, Outlook=happy" >
              <section name="Matt" type="Male, Outlook=neutral"/>
         </sectionGroup>
    </sectionGroup>
  </configSections>
</configuration>

The Script:

[XML] $xmlObj=Get-Content "C:\temp\infile.xml" -Raw

foreach ($elem in $xmlObj.configuration.configSections.sectionGroup.section)
    {
    Write-Host ("=> {0}='{1}'" -f $elem.name, $elem.type) 
    }

The output:

=>  Bobby='Male, Outlook=happy'
=>  Cathy='Female, Outlook=neutral'
=>  David='Male, History=Yes'

Note that is does not include the first name(Albert) or the two names in the second section (Mark, Matt).

I can't change the multiple XML files, so:

  1. what needs to change in the code to see all entries?
  2. When writing them back, are additional changes required as well?

Upvotes: 0

Views: 53

Answers (2)

Kent Thayer
Kent Thayer

Reputation: 11

Ok, solve it. Each is a different section, which needs to be specified. This returns all 6

$xmlObj.configuration.configSections.sectionGroup  | % { Write-Host ("=> {0}='{1}'" -f $_.name, $_.type) }

$xmlObj.configuration.configSections.sectionGroup.section | % { Write-Host ("=> {0}='{1}'" -f $_.name, $_.type) }

$xmlObj.configuration.configSections.sectionGroup.sectionGroup | % { Write-Host ("=> {0}='{1}'" -f $_.name, $_.type) }

$xmlObj.configuration.configSections.sectionGroup.sectionGroup.section | % { Write-Host ("=> {0}='{1}'" -f $_.name, $_.type) }

Upvotes: 0

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174445

Use an XPath expression to select all <section> elements regardless of location:

foreach($elem in $xmlObj.SelectNodes('//section')){
  # work with $elem
}

Upvotes: 1

Related Questions