微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决使用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;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。