将内部xml转换为powershell

时间:2016-04-30 03:55:17

标签: powershell dictionary xpath powershell-v2.0

我正在尝试使用PowerShell创建字典。以下是xml文件,

我正在研究代码,

$env = "Test"
$myDictionary = New-Object "System.Collections.Generic.Dictionary``2[System.String,System.String]"
$xmlfile = [xml] (Get-Content "file-name")  
$xmlfile.SelectNodes("descendant::configuration/environment[@id='$($env)']/descendant::text()[normalize-space()]") | ? Value | % { $myDictionary.Add($_.ParentNode.ToString(), $_.Value)  }

我希望输出如下,

Key            Value
----            -----
smtpserver      smtp1.org
type            test
encryption     <add key ="DB1" value="mhu0VrvzBBlYjPbxh+EQk0zdY"/>
               <add key ="DB2" value="DVvHAq2EVKF5fmYYiUUJ/g=="/>
               <add key="DB3" value="dkcdowefnwlwkli/" />

我想在字典中包含内部xml部分。有人可以为上述要求提出可能的解决方案吗?

提前致谢。

1 个答案:

答案 0 :(得分:3)

我建议使用以下XPath,它将返回匹配的<environment>所有直接子元素

//configuration/environment[@id='target_id_here']/*

然后使用$myDictionary.Add($_.ToString(), $_.InnerXml)将每个元素的名称和内部XML对添加到字典中。

演示:

PS C:\Users\har07> $xml = [xml]@"
>> <configuration>
>>   <environment id="Test">
>>     <smtpserver>smtp1.org</smtpserver>
>>     <type>test</type>
>>     <encryptioninfo>
>>       <add key ="DB1" value="mhu0VrvzBBlYjPbxh+EQk0zdY"/>
>>       <add key ="DB2" value="DVvHAq2EVKF5fmYYiUUJ/g=="/>
>>       <add key="DB3" value="dkcdowefnwlwkli/" />
>>     </encryptioninfo>
>>   </environment>
>> </configuration>
>> "@
PS C:\Users\har07> $env = "Test"
PS C:\Users\har07> $myDictionary = New-Object "System.Collections.Generic.Dictionary``2[System.String,System.String]"
PS C:\Users\har07> $xml.SelectNodes("//configuration/environment[@id='$($env)']/*") | % { $myDictionary.Add($_.ToString(), $_.InnerXml)  }
PS C:\Users\har07> $myDictionary

Key            Value
---            -----
smtpserver     smtp1.org
type           test
encryptioninfo <add key="DB1" value="mhu0VrvzBBlYjPbxh+EQk0zdY" /><add key="DB2" value="DVvHAq2EVKF5fmYYiUUJ/g==" />...