Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 help me with powershell code for this?

like image 699
Sitaram Pamarthi Avatar asked May 09 '11 07:05

Sitaram Pamarthi


2 Answers

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
like image 80
Enrico Campidoglio Avatar answered Sep 28 '22 10:09

Enrico Campidoglio


@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
like image 32
JPBlanc Avatar answered Sep 28 '22 10:09

JPBlanc