簡體   English   中英

使用LINQ to XML基於屬性與多個節點來獲取正確的節點

[英]Grabbing correct node based on attribute with multiple nodes using LINQ to XML

我在用LINQ編寫查詢以從XML文件中獲取所需數據時遇到了一些麻煩。

XML文件設置如下所示

<Study id ="">
  <Multi>
    <filepath id =""></filepath>
    <filepath id ="display"></filepath>
    <combined></combined>
  </Multi>
</Study>

<Study id ="">
  <Multi>
    <filepath id =""></filepath>
    <filepath id ="display"></filepath>
    <combined></combined>
  </Multi>
</Study>

我正在嘗試獲取其中id =“ display”的文件路徑節點的值

var displaySettingsQuery = (from n in _XML.Descendants("Study").Descendants("Multi")
                                    where n.Element("Multi").Attribute("id").Value == "display"
                                    select n.Element("filepath").Value);

這似乎不起作用,因為Element()方法僅獲取“ Multi”的第一個實例。 但是,如果我使用Elements(),則會收到語法錯誤,因為Elements是Ienumerable,所以我無法直接調用attribute。 我將如何遍歷“ Multi”集合以進行比較?

感謝您的協助。

如果使from子句返回<filepath>元素而不是<Multi> ,則這會更容易,因為您只關心whereselect子句中的<filepath>

var displaySettingsQuery = (from n in _XML.Descendants("Study")
                                          .Elements("Multi")
                                          .Elements("filepath")
                            where n.Attribute("id").Value == "display"
                            select n.Value);

暫無
暫無

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

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