簡體   English   中英

Powershell - XML - 如何從每個節點系列的不同深度提取多個值

[英]Powershell - XML - How do I extract multiple values from various depths per node family

我有幾百萬行 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.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

有關此主題的更多信息

微軟 - 選擇對象

4sysops - 在 powershell 中添加帶有選擇對象的計算屬性

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM