XML to Hash Table using Powershell

ぃ、小莉子 提交于 2019-11-30 04:38:58

问题


I want to convert XML :

<TEST>
    <ipAddress value="10.2.1.90"/>
    <gitDir value="C:\git\project"/>
    <gitArchiveDir value="C:\git\archive"/>
    <apacheDocroot value="/var/www"/>
    <apacheUsername value="root"/>
</TEST>

Into a hash table :

Name             Value

ipAddress        10.2.1.90
gitDir           C:\git\project
gitArchiveDir    C:\git\archive
apacheDocroot    /var/www
apacheUsername   root

Currently using this read method:

$invocation = (Get-Variable MyInvocation).Value
$directorypath = Split-Path $invocation.MyCommand.Path
$File = $directorypath + '\config.xml'
$CONFIG = "CONFIG"
$CFG = [xml] ( gc $File )

$CFG.test.ipAddress

回答1:


This should do the trick:

PS C:\> $CFG = [xml]@'
>> <TEST>
>>     <ipAddress value="10.2.1.90"/>
>>     <gitDir value="C:\git\project"/>
>>     <gitArchiveDir value="C:\git\archive"/>
>>     <apacheDocroot value="/var/www"/>
>>     <apacheUsername value="root"/>
>> </TEST>
>> '@
>>
PS C:\> $ht = @{}
PS C:\> $CFG.test.ChildNodes | Foreach {$ht[$_.Name] = $_.Value}
PS C:\> $ht

Name                           Value
----                           -----
apacheUsername                 root
gitArchiveDir                  C:\git\archive
ipAddress                      10.2.1.90
apacheDocroot                  /var/www
gitDir                         C:\git\project


来源:https://stackoverflow.com/questions/12409185/xml-to-hash-table-using-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!