user3721640
user3721640

Reputation: 947

Iterate XML in Powershell

I am working on an XML content (below) and wanted to iterate the value of the Student element and corresponding value of Gender, and then finally check if the student name is Anne, print the Gender as Female.

However when I try using below script, the output I get is-

Anne is Male
Anne is Male
Anne is Female

What could be the issue here? Could I get some help here?

XML content:

?xml version="1.0"?>
    <Objects>
      <Object Type="System.Management.Automation.CustomObject">
        <Property Name="Gender" Type="Application.String">Male</Property>
        <Property Name="Student" Type="Microsoft.Application.Service">John</Property>
      </Object>
      <Object Type="System.Management.Automation.CustomObject">
        <Property Name="Gender" Type="Application.String">Male</Property>
        <Property Name="Student" Type="Microsoft.Application.Service">Charles</Property>
      </Object>
    <Object Type="System.Management.Automation.CustomObject">
       <Property Name="Gender" Type="Application.String">Female</Property>
       <Property Name="Student" Type="Microsoft.Application.Service">Anne</Property>
    </Object>
</Objects>

Here is the script:

[xml]$file = Get-Content C:\xml-report.xml
foreach ($obj in $file.Objects.Object.Property) {
  if('Student'-contains $obj.Name) {
    $name = $obj.'#text'
    }
  if('Gender' -contains $obj.Name) {
    $gend = $obj.'#text'  
    }
       if ($name = "Anne") { 
       Write-Host $name "is" $gend
    }
}

Upvotes: 0

Views: 301

Answers (1)

arco444
arco444

Reputation: 22831

You need to start iterating over the objects rather than the properties for this, then select the relevant data from each property of the object.

You also need to use the correct syntax for testing equality, in Powershell it is -eq. For more info type Get-Help about_comparison_operators

Try:

foreach ($obj in $file.Objects.Object) {
  $gend = $obj.Property | ? { $_.Name -eq 'Gender' } | Select -expand '#text'
  $name = $obj.Property | ? { $_.Name -eq 'Student' } | Select -expand '#text'
  if ($name -eq 'Anne') {
    Write-Output "$name is $gend"
  }
}

The ? is an alias for Where-Object which allows you to filter a collection based on its properties.

Upvotes: 4

Related Questions