【发布时间】:2019-09-19 06:36:17
【问题描述】:
我必须解析下面的文件并在报告中显示一些标签。
<CommChannelQueryResponse>
<CommChannel>
<ChannelName>C1</ChannelName>
<AdapterAttribute>
<Name>Filename</Name>
<Value>a.txt</Value>
</AdapterAttribute>
<AdapterAttribute>
<Name>Directory</Name>
<Value>/dir1</Value>
</AdapterAttribute>
<AdapterAttribute>
<Name>ArchiveDirectory</Name>
<Value>/archive1</Value>
</AdapterAttribute>
...
</CommChannel>
<CommChannel>
...
</CommChannelQueryResponse>
根据本论坛的另一篇帖子,我尝试了以下方法,它确实有效。
[xml]$XmlDocument = Get-Content commchannels.xml
$XmlDocument.CommChannelQueryResponse.CommChannel |
Format-Table -Property @{L="Name"; E={$_.ChannelName}},
@{L="Filename";Expression={$_.AdapterAttribute.Value[0]}}
名称 文件名
---- --------
C1 a.txt
C2 b.txt
我正在尝试对此进行改进,因为此代码依赖于“文件名”作为第一个属性。如何更改它以显示具有AdapterAttribute.Name = "Filename" 的AdapterAttribute.Value?
我尝试了以下操作,如您所见,“文件名”没有显示任何内容。
$XmlDocument.CommChannelQueryResponse.CommChannel |
Format-Table -Property @{L="Name";E={$_.ChannelName}},
@{L="Filename";Expression={
$_.AdapterAttribute.Value | Where-Object $_.AdapterAttribute.Name = "Filename"
}}
名称 文件名
---- --------
C1
C2
【问题讨论】:
-
$_.AdapterAttribute.Name = "Filename"->$_.AdapterAttribute.Name -eq "Filename"。=是赋值运算符,不是比较运算符。 -
谢谢安斯加尔。我尝试了 -eq ,它的行为与 "=" 相同
-
请不要发布代码截图。
-
$_.AdapterAttribute.Value | Where-Object $_.AdapterAttribute.Name = "Filename"->$_.AdapterAttribute | Where-Object {$_.Name -eq "Filename"} | Select-Object -Expand Value -
成功了,安斯加尔。谢谢你。为截图道歉!
标签: xml powershell parsing