直接访问XML中的键值对

时间:2012-02-13 10:47:38

标签: xml powershell

鉴于此示例XML数据,是否可以直接访问密钥?

例如:$ xml.root.User_Blob.LogonMethod

<?xml version="1.0" encoding="utf-16"?>
<root>
  <User_Blob>
    <Item>
      <Key>LogonMethod</Key>
      <Value>prompt</Value>
    </Item>
    <Item>
      <Key>ServerURLEntered</Key>
      <Value>http://myserver/config.xml</Value>
    </Item>
    <Item>
      <Key>ServerURLListUsers</Key>
      <Value>
        <LSOption>http://myurl/config.xml</LSOption>
        <LSOption>http://myurl</LSOption>
      </Value>
    </Item>
    <Item>
      <Key>UserDisplayDimensions</Key>
      <Value>fullscreen</Value>
    </Item>
  </User_Blob>

3 个答案:

答案 0 :(得分:5)

我个人需要Where-Object时,我会使用Select-Xml

$c = [xml]'<?xml version="1.0" encoding="utf-16"?>
<root>
  <User_Blob>
    <Item>
      <Key>LogonMethod</Key>
      <Value>prompt</Value>
    </Item>
    <Item>
      <Key>ServerURLEntered</Key>
      <Value>http://myserver/config.xml</Value>
    </Item>
    <Item>
      <Key>ServerURLListUsers</Key>
      <Value>
        <LSOption>http://myurl/config.xml</LSOption>
        <LSOption>http://myurl</LSOption>
      </Value>
    </Item>
    <Item>
      <Key>UserDisplayDimensions</Key>
      <Value>fullscreen</Value>
    </Item>
  </User_Blob></root>'
($c | Select-Xml -XPath "//Item[Key = 'LogonMethod']").Node.Value

它更干净(如果你知道你在做什么)。

答案 1 :(得分:3)

试试这个: -

[xml]$xmlObject = (New-Object System.Net.WebClient).DownloadString("Filepath")   

Write-Host $xmlObject.root.User_Blob.Item.Key

$xmlObject = New-Object XML
$xmlObject.Load("YourFilePath")
$xmlObject.root.User_Blob.Item.Key

要获取 LogonMethod 的值,请尝试以下方式: -

($xmlObject.root.User_Blob.Item | Where-Object { $_.Key -eq 'LogonMethod' }).Value

还是其他: -

$xmlObject.selectSingleNode("/root/User_Blob/Item[Key = 'LogonMethod']/Value").get_innerXml()

答案 2 :(得分:1)

您还可以使用SelectSingleNode方法:

$xml.SelectSingleNode("//*[Key='LogonMethod']").Value