将XML转换为字典

时间:2016-04-24 16:59:16

标签: xml powershell dictionary powershell-v2.0 powershell-v3.0

有人可以告诉我如何使用Powershell将xml文件转换为Dictionary。

这是我的xml文件,

==>     <xml id="ATAT_Prod">
        <tag1>value1</tag1>
        <tag2>value2</tag2>
        </xml>
有人可以建议我。提前谢谢。

1 个答案:

答案 0 :(得分:2)

您必须使用Get-Content cmdlet加载内容并将其强制转换为[xml]。使用SelectNodes cmdlet和xpath表达式选择所有后代并将其转换为哈希表

$xml = [xml] (Get-Content 'YOUR_PATH_HERE')     
$xml.SelectNodes("descendant::node()") | ? Value | % { @{$_.ParentNode = $_.Value}  }

输出:

Name                           Value                                                                                                                                                       
----                           -----                                                                                                                                                       
state                          Texas                                                                                                                                                       
environment                    Test                                                                                                                                                        
isEnabled                      False                                                                                                                                                       
filepath                       C:\xmlfile                                                                                                                                                  
test                           Test environement strings                                                                                                                                   
UAT                            UAT environment strings 

修改: 这是一个带有字典的工作示例:

$myDictionary = New-Object "System.Collections.Generic.Dictionary``2[System.String,System.String]"
$xml = [xml] (Get-Content 'YOUR_PATH_HERE')     
$xml.SelectNodes("descendant::node()") | ? Value | % $myDictionary.Add($_.ParentNode.ToString(), $_.Value)  }