使用PowerShell解析XML文件
问题描述:
我的应用程序之一是在XML文件下面生成的。使用PowerShell解析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中,你可以使用新的Select-Xml小命令和XPath表达解决这个问题:
[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
相关资源:
答
@Enrico坎皮多利奥给出了 “最干净” 这里的解决方案是一种古老的时尚。
PS> $xml = [XML](get-content c:\temp\yourfile.xml)
PS> $errcode = ($xml.root.command | where {$_.property.name -eq "PWR.WakeupOnLAN" }).property.errorcode
+1
+1,用于向后兼容。您的示例可以在PowerShell 1.0和2.0中使用。 – 2011-05-09 08:30:02
答
另一种可能性是创建函数。与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
+0
@all 感谢您的回答。这真的帮助了我。 – 2011-05-10 04:35:49
请标记更正的答案。 – JasonMArcher 2011-05-10 06:44:18