Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Powershell中迭代XML_Xml_Powershell - Fatal编程技术网

在Powershell中迭代XML

在Powershell中迭代XML,xml,powershell,Xml,Powershell,我正在处理一个XML内容(如下),希望迭代Student元素的值和相应的性别值,然后最后检查学生名是否为Anne,将性别打印为女性 然而,当我尝试使用下面的脚本时,我得到的输出是- Anne is Male Anne is Male Anne is Female 这里可能有什么问题?我能在这里得到一些帮助吗 XML内容: ?xml version="1.0"?> <Objects> <Object Type="System.Management.Au

我正在处理一个XML内容(如下),希望迭代Student元素的值和相应的性别值,然后最后检查学生名是否为Anne,将性别打印为女性

然而,当我尝试使用下面的脚本时,我得到的输出是-

Anne is Male
Anne is Male
Anne is Female
这里可能有什么问题?我能在这里得到一些帮助吗

XML内容:

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

您需要开始迭代对象而不是属性,然后从对象的每个属性中选择相关数据

您还需要使用正确的语法来测试相等性,在Powershell中是
-eq
。有关更多信息,请键入
获取有关\u比较\u运算符的帮助

尝试:


Where对象
的别名,允许您根据其属性筛选集合

您需要开始迭代对象而不是属性,然后从对象的每个属性中选择相关数据

您还需要使用正确的语法来测试相等性,在Powershell中是
-eq
。有关更多信息,请键入
获取有关\u比较\u运算符的帮助

尝试:


Where对象
的别名,允许您根据其属性筛选集合

您的XML看起来像是
Export-CliXml
的输出。为什么不使用
Import-CliXml
?@BaconBits对我来说,它看起来像是
ConvertTo-Xml
的结果,它使用的格式与
Export-CliXml
不同,并且没有
ConvertFrom
/
Import
命令。是的,Xml文件是使用ConvertTo-Xml cmdlet创建的。有没有更简单的转换为XML的方法?您的XML看起来像是
Export-CliXml
的输出。为什么不使用
Import-CliXml
?@BaconBits对我来说,它看起来像是
ConvertTo-Xml
的结果,它使用的格式与
Export-CliXml
不同,并且没有
ConvertFrom
/
Import
命令。是的,Xml文件是使用ConvertTo-Xml cmdlet创建的。有没有更简单的转换为XML的方法?
[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
    }
}
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"
  }
}