我有以下 XML(這是較大檔案的一部分):
<class type="I want to filter on whatever value this is">
<instance name="QuestionSet4">
<property name="QuestionSetName">QuestionSet4</property>
<property name="Ratio">5</property>
</instance>
<instance name="QuestionSetTrust">
<property name="QuestionSetName">QuestionSetTrust</property>
<property name="Ratio">5</property>
</instance>
</class>
我的目標是使用 PowerShell,Select-Xml這樣我就可以name使用過濾 class 的 XPath回傳每個節點的兩個屬性type,以便輸出如下所示:
QuestionSetName, Ratio
QuestionSet4, 5
QuestionSetTrust, 5
該類type在檔案中是唯一的,所以我想知道是否可以基于它進行過濾,而不是像下面這樣對元素進行硬編碼:
/root/class[3]/@type
而是 /root/class/@type="I want to filter on whatever value this is"...
實體名稱會因檔案而異,因此我也無法對此進行過濾。
uj5u.com熱心網友回復:
您可以instance使用 XPath 運算式決議相關節點,如下所示:
//class[@type = 'I want to filter on whatever value this is']/instance
因此,您可以像這樣構造所需的輸出物件:
$xml |Select-Xml -XPath "//class[@type = 'I want to filter on whatever value this is']/instance" |ForEach-Object {
[pscustomobject]@{
QuestionSetName = ($_.Node |Select-Xml "./property[@name='QuestionSetName']").Node.InnerText
Ratio = ($_.Node |Select-Xml "./property[@name='Ratio']").Node.InnerText
}
}
如果您<property />要為每個元素列舉很多元素,<instance />它會很快變得混亂,但您可以像這樣稍微簡化它:
$propertyNames = 'QuestionSetName','Ratio','Size','SomeOtherProperty'
$xml |Select-Xml -XPath "//class[@type = 'I want to filter on whatever value this is']/instance" |ForEach-Object {
$properties = [ordered]@{}
foreach($name in $propertyNames){
$properties[$name] = ($_.Node |Select-Xml "./property[@name='${name}']").Node.InnerText
}
[pscustomobject]$properties
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/358628.html
