在Powershell中迭代XML
我正在处理一个XML内容(如下),希望迭代Student元素的值和相应的性别值,然后最后检查学生名是否为Anne,将性别打印为女性 然而,当我尝试使用下面的脚本时,我得到的输出是-在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
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"
}
}