开发者

Parsing an XML file with PowerShell

One of my application is generating below XML file.

<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>

I am interested in reading the value and errorcodes of "PWR.WakeupOnLAN" property name. Before posting here, I tried various things but couldn't find correct code for reading properties in powershell. Can any one h开发者_运维百科elp me with powershell code for this?


In PowerShell 2.0 you can solve this using the new Select-Xml cmdlet and an XPath expression:

[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

Related resources:

  • Select-Xml
  • Processing XML with PowerShell
  • XmlDocument Class
  • XmlAttribute Class


@Enrico Campidoglio gives the "cleanest" solution here is a kind of old fashion.

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


Another possibility, is to create a function. Similar to JPBlanc's solution.

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜