.net 使用PowerShell解析XML文件

.net 使用PowerShell解析XML文件,.net,powershell,powershell-2.0,.net,Powershell,Powershell 2.0,我的一个应用程序正在生成下面的XML文件 <root> <command name="Set"> <property name="PWR.WakeupOnLAN" value="6" errorcode="0x0"/> </command> <command name="Set"> </command> <command name="biossettings"&g

我的一个应用程序正在生成下面的XML文件

<root>
    <command name="Set">
        <property name="PWR.WakeupOnLAN" value="6" errorcode="0x0"/>
    </command>
    <command name="Set">
    </command>
    <command name="biossettings">
        <property name="task" value="Succeeded." errorcode="0x0"/>
    </command>
</root>


我对阅读“PWR.WakeupOnLAN”属性名的值和错误代码感兴趣。在这里发布之前,我尝试了各种方法,但在powershell中找不到读取属性的正确代码。有人能帮我提供有关此问题的powershell代码吗?

在powershell 2.0中,您可以使用新的cmdlet和表达式解决此问题:

[xml]$document = "<root><command name='Set'><property name='PWR.WakeupOnLAN' value='6' errorcode='0x0'/></command><command name='Set'></command><command name='biossettings'><property name='task' value='Succeeded.' errorcode='0x0'/></command>"

$value = (Select-Xml -Xpath "//property[@name='PWR.WakeupOnLAN']/@value" $document).Node.Value
$errorCode = (Select-Xml -Xpath "//property[@name='PWR.WakeupOnLAN']/@errorcode" $document).Node.Value
[xml]$document=“”
$value=(选择Xml-Xpath//property[@name='PWR.WakeupOnLAN']/@value“$document)。Node.value
$errorCode=(选择Xml-Xpath”//property[@name='PWR.WakeupOnLAN']/@errorCode“$document)。Node.Value
相关资源:


    • @Enrico Campidoglio提供了“最干净”的解决方案,这是一种古老的时尚

      PS> $xml = [XML](get-content c:\temp\yourfile.xml)
      PS> $errcode = ($xml.root.command | where {$_.property.name -eq "PWR.WakeupOnLAN" }).property.errorcode
      

      另一种可能性是创建一个函数。类似于JPBlanc的解决方案

      function Get-Info ($name='PWR.WakeupOnLAN', $targetXml){
          $properties = $targetXml.GetElementsByTagName("property") 
          $properties | Where {$_.Name -eq $name}
      }
      
      Get-Info -targetXml $xml
      Get-Info -name Task -targetXml $xml
      

      +1用于向后兼容性。您的示例可以在PowerShell 1.0和2.0中使用。@谢谢您的回答。这些确实帮助了我。请标出正确的答案。