1

我有几百万行要解析的 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}
...
...

有没有办法清理这个,或者另一种更有效的方法?

4

1 回答 1

0

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

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

以下是您需要在您的场景中执行此操作的方式。

该声明

$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 - 选择对象

4sysops - 在 powershell 中使用选择对象添加计算属性

于 2020-01-14T23:35:33.777 回答