2017-08-30 88 views
1

在PowerShell中,我試圖檢索使用XPath屬性的值。在下面的例子中,我想爲「hi」類別獲得「name」的值,這將是「新測試」。使用XPath檢索屬性值的特定屬性

示例代碼所示:

<Report name="test" category="thisone"> 
    <String>test</String> 
    <String>test2</String> 
    <Report name="new test" category="hi"> 
    <String>hello</String> 
    <String>hi again</String> 
    </Report> 
</Report> 

這是我有:

Select-Xml -XPath "//Report[@name='test']/Report" | Select name | 
    Out-File "result.txt" 

我的結果是:

 
name 
---- 

我並不真的需要指定類別屬性因爲<Report>標籤將永遠在第一個<Report> ta之後g,所以這就是爲什麼我認爲使用XPath會更容易。

回答

2

您需要首先展開節點。 Select-XML正在提供該對象。如果你這樣做:

Select-Xml -Xml $XML -XPath "//Report[@name='test']/Report" 

你會得到

節點:報告

路徑:InputStream的

模式://報告[@名稱= '測試'] /報告

一旦展開「節點」,你會得到一堆更多的屬性

Select-Xml -Xml $XML -xPath "//Report[@name='test']/Report" | Select-Object –ExpandProperty 「node」 | select * 

名稱:新的測試

類別:喜

字符串:{你好,喜再次}

的localName:報告

...等...等

以下完整概念

[xml]$XML = @" 
<Report name="test" category="thisone"> 
<String>test</String> 
<String>test2</String> 
    <Report name="new test" category="hi"> 
    <String>hello</String> 
    <String>hi again</String> 
    </Report> 
</Report> 
"@ 

Select-Xml -Xml $XML -xPath "//Report[@name='test']/Report" | Select-Object –ExpandProperty 「node」 | select name 
+0

完美是做到了!順便說一句,我可以將該值放入一個變量中,在該語句之前添加諸如$ hi =的內容嗎?我目前正在使用Out-File到一個文本文件,並且我看到它寫入了「name」和「----」,然後是下面的值,我並不真正關心這兩行並試圖消除它們。 。 – Awsmike

+0

'選擇的XML-XML $ XML -xPath 「//報告[@名稱= '測試'] /報告」 | Select-Object -ExpandProperty「節點」| foreach-object {$ _。name} | Out-file「HELLO.TXT」' – ArcSet

+0

好!這也工作得很好!有沒有一種方法可以將它分配給一個變量?我試過了,我得到這個:命令流水線位置的cmdlet Select-Xml 1 以下參數的供應值: Xml [0]: – Awsmike

0

XPath可以直接獲取屬性的值。

(Select-Xml -Xml $XML -xPath "//Report[@name='test']/Report/@name").Node.Value 

(但仍需要提取值形成最終[XmlAttribute]