![](/img/trans.png)
[英]C# Linq XML Query where multiple elements of same name from a parent node based on a child node value
[英]Select one node from others with same name with Linq to XML and C#
我遇到了一個XML文件和C#問題。 xml文件如下所示:
<data>
<weather>
//some stuff
</weather>
<weather>
//some stuff
</weather>
<weather>
//some stuff
</weather>
<weather>
//some stuff
</weather>
現在我的問題是:
例如,我只需要導航到第三個節點。 現在,我以為可以用以下方法解決它:
act_tempereature = wData.Root.Element("weather").Element("maxtempC").Value;
但是,當然,它只選擇具有該特定名稱的Document目錄中的第一個Element。 那么,我該如何導航到第三或第二天氣?
如果已經問過這個問題,對不起,因為我沒有找到任何東西(也許我只是搜索了錯誤的關鍵字:/)
希望你能幫忙
您可以使用帶有復數s
Elements()
來獲取具有特定名稱的所有元素:
act_tempereatures = wData.Root
.Elements("weather")
.Elements("maxtempC")
.Select(o => o.Value);
然后,只需使用foreach
循環即可獲取每個溫度值。 或者,如果僅在特定位置需要一個元素,例如第三個元素,請嘗試使用Skip()
和Take()
:
act_tempereature3 = wData.Root
.Elements("weather")
.Skip(2)
.Take(1)
.Elements("maxtempC")
.Select(o => o.Value);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.