问题描述
配置文件,如下所示:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Environment" value="Dev Environment"/>
</appSettings>
</configuration>
如何在Powershell中获取键环境"的值?我的意思是,当您选择键环境"时,它应该返回开发环境".
How can i get the value of key "Environment" in Powershell? I mean it should return "Dev Environment" when you select key "Environment".
我更喜欢linq在这里使用任何有真正想法的人.
I prefer linq to use here anyone with any idea really appreciate that.
推荐答案
我建议 xpath .
首先创建一个 XmlDocument 对象,如下所示:
First create an XmlDocument object like this:
$xml = [xml] @'
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Environment" value="Dev Environment"/>
</appSettings>
</configuration>
'@
...或这样:
$xml = [xml] (Get-Content C:\file.xml)
然后使用SelectNodes或SelectSingleNode方法并提供xpath作为参数.xpath是特定于域的语言,可能会变得有些复杂.这个xpath查询说给我所有名为add的节点的属性命名值,这些节点的属性名为key的值为Environment.
Then use the SelectNodes or SelectSingleNode method and provide your xpath as an argument. xpath is domain specific language and can get somewhat complicated. This xpath query says give me the attribue named value of all nodes named add that have an attribute named key with the value of Environment.
$xml.SelectNodes('//add[@key="Environment"]/@value')[0].'#text'
PowerShell在XmlElement和XmlAttribute对象上添加了一个 #text
NoteProperty,可用于访问节点的文本.
PowerShell adds a #text
NoteProperty on XmlElement and XmlAttribute objects you can use to access the text of the node.
这篇关于在Powershell中获取app.config元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!