0

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
    }
}
3
  • 3
    Your XML looks like it's the output of Export-CliXml. Why not use Import-CliXml? Commented Nov 12, 2015 at 14:24
  • @BaconBits For me it looks like result of ConvertTo-Xml, which AFAIK use different format than Export-CliXml and does not have ConvertFrom/Import command. Commented Nov 12, 2015 at 14:52
  • Yes PetSerAl, the XML file was created using ConvertTo-Xml cmdlet. Is there a simpler way of converting to XML? Commented Nov 12, 2015 at 16:01

1 Answer 1

4

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.

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

Comments

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.