【发布时间】:2017-01-26 13:11:14
【问题描述】:
我正在尝试将以下 xml 文件转换为 PowerShell 字典。
<configuration>
<environment id="Test">
<client>ABC</client>
<type>Test</type>
<template> </template>
<targetmachines>
<targetmachine>
<name>Any</name>
<remotedirectory>C:\ServiceDirectory</remotedirectory>
</targetmachine>
</targetmachines>
<connectionStrings>
<DB1>User ID=xx;password=xx=;</DB1>
<DB2>User ID=yy;password=yy=;</DB2>
</connectionStrings>
</environment>
</configuration>
这是我的 powershell 脚本:
$environmentId = "Test"
$configxml = [xml] (Get-Content "xmlfile")
$keyValuePairs = New-Object "System.Collections.Generic.Dictionary``2[System.String,System.String]"
$configxml.SelectNodes("descendant::configuration/environment[@id='$($environmentId)']/descendant::text()[normalize-space()]") | Where-Object {$_.Value} |
ForEach-Object {
$keyValuePairs.Add($_.ParentNode.ToString(), $_.Value)
}
Write-Output $keyValuePairs
我得到以下输出:
Key Value
--- -----
client ABC
type Test
name Any
remotedirectory C:\ServiceDirectory
DB1 User ID=xx;password=xx=;
DB2 User ID=yy;password=yy=;
上面的 PowerShell 脚本运行良好。但我想要以下输出。这里的区别是我们有一个名为“模板”的额外键,它有空值。我想将空值元素转换为字典。
Key Value
--- -----
client ABC
type Test
template
name Any
remotedirectory C:\ServiceDirectory
DB1 User ID=xx;password=xx=;
DB2 User ID=yy;password=yy=;
有人可以建议我如何更新我的 powershell 脚本。提前致谢。
【问题讨论】:
-
.//configuration/environment[@id='$($environmentId)']//*[not(*)] -
嗨,出现以下错误,使用“1”参数调用“SelectNodes”的异常:“'descendant::configuration/environment[@id='Test']/descendant::* [not(*)]' 的令牌无效。"
-
我不知道为什么,但是 StackOverflow 在
not之后插入了两个不可打印的字符。您需要删除它们。 -
能否请您发布完整的解决方案
-
那些插入的字符是
U+200C零宽度非连接符和U+200Bnot和(*)之间的零宽度空间。
标签: xml powershell dictionary powershell-2.0