【问题标题】:Read XML file using PowerShell and select tags based on conditions使用 PowerShell 读取 XML 文件并根据条件选择标签
【发布时间】: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


【解决方案1】:

不知道要不要进入 Xpath 表达式...(区分大小写)

(select-xml "/CommChannelQueryResponse/CommChannel/AdapterAttribute" file.xml).node

Name             Value
----             -----
Filename         a.txt
Directory        /dir1
ArchiveDirectory /archive1

(select-xml "/CommChannelQueryResponse/CommChannel/AdapterAttribute[Name/text()='Filename']" file.xml).node

Name     Value
----     -----
Filename a.txt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-18
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    相关资源
    最近更新 更多