首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用powershell读取xml文件并将键值存储在哈希表中

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

Stack Overflow用户
提问于 2021-07-21 05:31:13
回答 1查看 75关注 0票数 0

我需要读取以下xml文件,并将其存储在哈希表中。

代码语言:javascript
复制
<?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下面编写,并能够获得属性键值,但我需要将其存储在哈希表中,以便可以根据需要检索该值。

代码语言:javascript
复制
$URLS = [xml](Get-Content 'C:\Desktop\Variables.xml')

$URLS.ConfigValues.Dev.item | where {$_.key -eq 'connCVRC'}
代码语言:javascript
复制
Key      Value
---      -----
connCVRC Data Source=xlvxdev.cumulus.com,1615;Initial Catalog=FPTR_XLVX;Security=true;
EN

回答 1

Stack Overflow用户

发布于 2021-07-21 05:50:18

代码语言:javascript
复制
# 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

以上结果如下:

代码语言:javascript
复制
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;
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68461585

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档