我有以下格式的示例xml文件。如何使用Powershell直接访问键的值?
例如:$ xml.array.dict.key.name - >鲍勃,凯特,约翰
$xml = @'
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
<dict>
<key>name</key>
<string>bob</string>
<key>age</key>
<string>35</string>
<key>gender</key>
<string>male</string>
</dict>
<dict>
<key>name</key>
<string>kate</string>
<key>age</key>
<string>12</string>
<key>gender</key>
<string>female</string>
</dict>
<dict>
<key>name</key>
<string>john</string>
<key>age</key>
<string>57</string>
<key>gender</key>
<string>male</string>
</dict>
</array>
</plist>
'@
如何将xml转换为Powershell对象,如下所示?
输出
name age gender
--- -- -----
bob 35 male
kate 12 female
john 57 male
这就是我的尝试。
$xmldata = [xml]$xml
$xmldict = $xmldata.plist.array.dict
$xmldict
这给出了输出
key string
--- ------
{name, age, gender} {bob, 35, male}
{name, age, gender} {kate, 12, female}
{name, age, gender} {john, 57, male}
$ xmldict.key
name
age
gender
name
age
gender
name
age
gender
答案 0 :(得分:4)
这是一种奇怪的格式,你依赖于键/字符串元素对的顺序。但是,这对您的XML进行了测试:
$xml.plist.array.dict |
Foreach {
$vals = $_.SelectNodes('string'); $_.SelectNodes('key') |
Foreach {$ht=@{};$i=0} {$ht[$_.'#text'] = $vals[$i++].'#text'} `
{new-object psobject -property $ht}
}
这个版本本质上更通用 - 不依赖于string
元素名称:
$xml.plist.array.dict |
Foreach {
$_.SelectNodes('key') |
Foreach {$ht=@{}} {$ht[$_.'#text'] = $_.NextSibling.'#text'} `
{new-object psobject -property $ht}
}