【问题标题】:Filtering xml using Powershell Where-Object使用 Powershell Where-Object 过滤 xml
【发布时间】:2014-04-16 00:14:26
【问题描述】:

任务是将以下xml代码读回Powershell并仅显示具有属性的项目:event="1"。

xml file created by Powershell script createsim.ps1
<?xml version="1.0" encoding="utf-8"?>
<simulation name="Protocal Simulation">
  <duration type="clock">100000</duration>
  <density>1.1</density>
  <ideal_degree>12</ideal_degree>
  <radius>86</radius>
  <supportedchannels>[1,4,7,9,11,13]</supportedchannels>
  <class>Field.RandomField</class>
  <width>1000</width>
  <height>1000</height>
  <description event="1">Re-form the network</description>
  <action event="1">densityChangeDetected()</action>
  <description event="2">End the simulation</description>
  <action event="2">end()</action>
</simulation>"

脚本的管道输出和导出对象。

PS C:\scripts> C:\scripts\createsim.ps1 | Export-Clixml C:\scripts\simtemp.xml

正在导入对象。

PS C:\scripts> $simxml = Import-Clixml C:\scripts\simtemp.xml

寻找事件属性。

PS C:\scripts> $xmlout = $simxml | Where-Object ($_.event -eq 1) | Sort-Object event

PS C:\scripts> $xmlout

PS C:\scripts> write-host $xmlout

没有错误消息,也没有打印出来。

如果有任何帮助或提示,我将不胜感激。我在 Windows 8.1 上使用 Powershell 4.0

【问题讨论】:

  • 您确定在 Windows 8.1 上使用 PowerShell 2.0 吗?
  • 抱歉是第4版

标签: xml powershell


【解决方案1】:

我不确定我是否理解为什么需要 Export-Clixml。如果createsim.ps1 生成 XML,您可以直接使用该 XML,无需导出和导入。然后你的工作变得容易多了。假设您的脚本生成您帖子中提到的 XML,此代码:

   > $xml = [XML](Get-Content C:\scripts\createsim.ps1)
   > foreach ($node in $xml.simulation.ChildNodes)
     {
        if ($node.event -eq 1) { $node.OuterXml }
     }

给你:

   <description event="1">Re-form the network</description>
   <action event="1">densityChangeDetected()</action>

【讨论】:

  • 感谢您的帮助。当我运行您的代码时,我收到此错误。无法将值“System.Object []”转换为类型“System.Xml.XmlDocument”。错误:“指定的节点不能作为该节点的有效子节点插入,因为指定的节点类型错误。”在 C:\scripts\event.ps1:1 char:1 + $xml = [XML](C:\scripts\createsim.ps1) + ~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [], RuntimeException + FullyQualifiedErrorId : InvalidCastToXmlDocument
  • 感谢 djs 的提示!在我调整了你的代码之后,我让它工作了: PS C:\scripts> [XML]$xml = Get-Content C:\scripts\simulation.xml foreach ($node in $xml.simulation.ChildNodes) { if ( $node.event -eq 1) { $node.OuterXml } } 重构网络densityChangeDetected()
  • +1 它可以添加Get-content 我使用select-xml 添加解决方案。
【解决方案2】:

您可以尝试使用@djs 解决方案:

$xml = [XML](Get-Content(C:\scripts\createsim.ps1))

你可以 Select-Xml CmdLet 试试:

Select-Xml -Path "C:\temp\test.xml" -XPath "/simulation/action[@event]" | % {$_.node}

Select-Xml -Path "C:\temp\test.xml" -XPath "/simulation/action" | where {$_.node.event -eq '1'} | % {$_.Node.OuterXml}

对于与@djs 相同的结果:

Select-Xml -Path "C:\temp\test.xml" -XPath "/simulation/*[@event]" | where {$_.node.event -eq '1'} | % {$_.Node.OuterXml}

【讨论】:

  • 感谢 JPBlanc 的帮助,感谢您抽出宝贵时间帮助我。
猜你喜欢
  • 2021-05-21
  • 1970-01-01
  • 2016-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-29
  • 2018-11-30
相关资源
最近更新 更多