使用powershell读取xml文件并将键值存储在哈希表中

问题描述

我需要阅读下面的 xml 文件并将其存储在哈希表中。

<?xml version="1.0"?>
<ConfigValues>
   <Dev>
     <item Key="dbconn" Value ="Data Source=xlvxdev.cumulus.com,1615;Initial Catalog=FPTR_XLVX;Security=true;"/>
   </Dev>
   <QA>
     <item Key="dbconn" Value ="Data Source=xlvxqa.cumulus.com,1615;Initial Catalog=OPSR_CVRC;Security=true;"/>
   </QA>
   <PP>
     <item Key="dbconn" Value ="Data Source=xlvxpreprd.cumulus.com,1615;Initial Catalog=OPSR_CVRC;Security=true;"/>
   </PP>
   <PROD>
     <item Key="dbconn" Value ="Data Source=xlvxprd.cumulus.com,1615;Initial Catalog=OPSR_CVRC;Security=true;"/>
   </PROD>
</ConfigValues>

我尝试在 powershell 下编写并能够获取属性键值,但我需要将其存储在哈希表中,以便我可以根据需要检索该值。

$URLS = [xml](Get-Content 'C:\Desktop\Variables.xml')

$URLS.ConfigValues.Dev.item | where {$_.key -eq 'connCVRC'}
Key      Value
---      -----
connCVRC Data Source=xlvxdev.cumulus.com,1615;Initial Catalog=FPTR_XLVX;Security=true;

解决方法

# Parse the XML file into an XML DOM
($xml = [xml]::new()).Load((Convert-Path C:\Desktop\Variables.xml))

# Initialize the (ordered) output hashtable.
$hash = [ordered] @{}

# Populate the hashtable with the <ConfigValues> child element 
# names as the key,and their <item> child's Value attribute as the value.
$xml.ConfigValues.ChildNodes.ForEach({
   $hash[$_.Name] = $_.item.Value
})

$hash # output

以上产生:

Name                           Value
----                           -----
Dev                            Data Source=xlvxdev.cumulus.com,1615;Initial Catalog=FPTR_XLVX;Security=true;
QA                             Data Source=xlvxqa.cumulus.com,1615;Initial Catalog=OPSR_CVRC;Security=true;
PP                             Data Source=xlvxpreprd.cumulus.com,1615;Initial Catalog=OPSR_CVRC;Security=true;
PROD                           Data Source=xlvxprd.cumulus.com,1615;Initial Catalog=OPSR_CVRC;Security=true;