以下脚本
$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>
答案 0 :(得分:2)
使用ConvertTo-Xml
(内容对应Export-CliXml
,虽然有different output format),所需格式的最接近需要添加{ {1}}开关,它相当于:
-NoTypeInformation
要获得所需的输出,您必须手动创建XML :
<Objects>
<Object>
<Property Name="Key">1</Property>
<Property Name="Value">True</Property>
<Property Name="Key">2</Property>
<Property Name="Value">False</Property>
</Object>
</Objects>
请注意,需要使用$d.GetEnumerator() | ForEach-Object { '<Objects>' } {
' <Object Key="{0}" Value="{1}" />' -f $_.Key, $_.Value
} { '</Objects>'}
才能通过管道单独发送键值对;默认情况下,PowerShell不会枚举管道中的哈希表/字典条目。