直接访问XML中的键值对

Rem*_*mko 3 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>
Run Code Online (Sandbox Code Playgroud)

Siv*_*ran 5

尝试这个:-

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

Write-Host $xmlObject.root.User_Blob.Item.Key
Run Code Online (Sandbox Code Playgroud)

或者

$xmlObject = New-Object XML
$xmlObject.Load("YourFilePath")
$xmlObject.root.User_Blob.Item.Key
Run Code Online (Sandbox Code Playgroud)

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

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

或者

还是其他方式:-

$xmlObject.selectSingleNode("/root/User_Blob/Item[Key = 'LogonMethod']/Value").get_innerXml()
Run Code Online (Sandbox Code Playgroud)


ste*_*tej 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
Run Code Online (Sandbox Code Playgroud)

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