【问题标题】:Powershell - XML - How do I extract multiple values from various depths per node familyPowershell - XML - 如何从每个节点系列的不同深度提取多个值
【发布时间】:2020-01-14 23:11:50
【问题描述】:

我有几百万行要解析的 xml。 对于一个应用程序,我希望提取 3 条数据用于其他脚本。

xml 如下所示(每个分组已删除了几十个标签) 如果有帮助,我可以更改其中一个名称标签;虽然不可取,但它需要一些中间处理。 并非所有节点组都具有扩展属性。

<?xml version="1.0" encoding="IBM437"?>
<topo>
    <node>
        <name>device1Name</name>
         <extendedAttributes>
            <attribute>
                <name>tagCategoryName</name>
                <value>tagValue</value>
            </attribute>
        </extendedAttributes>
     </node>
    <node>
        <name>device2Name</name>
        <extendedAttributes>
            <attribute>
                <name>tagCategoryName</name>
                <value>tagValue</value>
            </attribute>
        </extendedAttributes>
    </node>
    <node>
        <name>device3Name</name>
    </node>
...
...
</topo>

我正在寻找每个节点的输出是

deviceName   tagCategoryName   tagValue

我尝试了几种方法,但都无法找到一个优雅的解决方案。 开始于

$xml = [xml](get-content prodnodes.txt)

尝试了一些带有 xpath 的 Select-Xml,直接使用 $xml.topo.node 寻址管道来使用属性名称选择对象。我无法使用以下内容有效地定位这些名称。

$xml.topo.node | select-object -property name, extendedAttributes.attribute.name, extendedAttributes.attribute.value

它只会返回名称 以下内容为我提供了一个额外的属性,但我无法毫无问题地扩展它。

$munge = $xml.topo.node | select-object -property name, {$_.extendedAttributes.attribute.name}

尝试扩展它看起来像这样

$munge = $xml.topo.node | select-object -property name, {$_.extendedAttributes.attribute.name, $_.extendedAttributes.attribute.value}

它给出了这样的输出

deviceName1   {tagCategoryName1, tagValue1}
deviceName2   {tagCategoryName1, tagValue2}
deviceName3   {$null, $null}
deviceName4   {tagCategoryName2, tagValue3}
...
...

有没有办法解决这个问题,或者其他更有效的方法?

【问题讨论】:

    标签: xml powershell xpath select-xml


    【解决方案1】:

    您的第一种方法几乎是正确的。 话虽如此,为了深入研究这样的属性,您需要使用计算属性。

    计算的属性由一个哈希表表示,其中包含一个名称元素,该元素将是您的列名,以及一个包含脚本块的表达式元素,用于执行比简单选择更多的操作。

    在你的场景中你需要这样做。

    声明

    $xml.topo.node | select-object -property name, 
    @{'Name' = 'TagName' ; 'Expression' = { $_.extendedAttributes.attribute.name } },
    @{'Name' = 'TagValue' ; 'Expression' = {$_.extendedAttributes.attribute.value}}
    

    结果

    name        TagName         TagValue
    ----        -------         --------
    device1Name tagCategoryName tagValue
    device2Name tagCategoryName tagValue
    device3Name
    

    有关此主题的更多信息

    Microsoft - Select-Object

    4sysops - Add a calculated property with select object in powershell

    【讨论】:

      猜你喜欢
      • 2020-05-05
      • 1970-01-01
      • 2022-01-28
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 2014-04-06
      相关资源
      最近更新 更多