mahesh
mahesh

Reputation: 478

Convert XML to Dictionary

Can someone please tell me how to convert the xml file to Dictionary using Powershell.

Here is my xml file looks like,

==>     <xml id="ATAT_Prod">
        <tag1>value1</tag1>
        <tag2>value2</tag2>
        </xml>

can someone suggest me. Thanks in advance.

Upvotes: 1

Views: 1652

Answers (1)

Martin Brandl
Martin Brandl

Reputation: 59011

You have to load the content using the Get-Content cmdlet and cast it to [xml]. Use the SelectNodescmdlet and a xpath expression to select all descendants and convert it to a hashtable:

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

Output:

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

Edit: Here is a working example with a dictionary:

$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)  }

Upvotes: 2

Related Questions