以下脚本
$d = New-Object -TypeName 'System.Collections.Generic.Dictionary[int, bool]'
$d.Add(1, $true)
$d.Add(2, $false)
($d | ConvertTo-Xml).DocumentElement.OuterXml
退货
<Objects>
<Object Type="System.Collections.Generic.Dictionary`2[System.Int32,System.Boolean]">
<Property Name="Key" Type="System.Int32">1</Property>
<Property Name="Value" Type="System.Boolean">True</Property>
<Property Name="Key" Type="System.Int32">2</Property>
<Property Name="Value" Type="System.Boolean">False</Property>
</Object>
</Objects>
但是,它可以返回以下内容吗?
<Objects>
<Object Key="1" Value="True" />
<Object Key="2" Value="False" />
</Objects>
最佳答案
使用 ConvertTo-Xml
(虽然是 Export-CliXml
,但它是different output format在内存中的对应项),但最接近所需格式的代码需要添加-NoTypeInformation
开关,这相当于:
<Objects>
<Object>
<Property Name="Key">1</Property>
<Property Name="Value">True</Property>
<Property Name="Key">2</Property>
<Property Name="Value">False</Property>
</Object>
</Objects>
要获得所需的输出,您必须手动创建XML :
$d.GetEnumerator() | ForEach-Object { '<Objects>' } {
' <Object Key="{0}" Value="{1}" />' -f $_.Key, $_.Value
} { '</Objects>'}
注意需要使用
.GetEnumerator()
以便通过管道分别发送键值对;默认情况下,PowerShell不枚举管道中的哈希表/字典条目。