2014-09-02 63 views
2

特定屬性選擇節點我想我的LINQ語句在下面的例子只的CustomField與NAME =「必需」與使用LINQ

<root> 
    <appinfo> 
     <application app_id=1234 app_name="SomeName"> 
     <customfield name="Required" value="123" /> 
     <customfield name="Not Required" value="234" /> 
     <customfield name="Not Required" value="345" /> 
     <customfield name="Not Required" value="456" /> 
     <customfield name="Not Required" value="678" /> 
     </application> 
    </appinfo> 
    ... 
    </root> 

1234,SomeName,123只需要在採摘這種情況下

下面是我試過的陳述。評論在哪裏不工作

var appAI = 
     from appinfo in doc.Root.Elements() 

     let application = appinfo.Elements().First() 
     let custom_field = application.Descendants() 

     //.Where(x => (string)x.Attribute("name") == "Required" && (string)x.Attribute("value").Value !="") 
     select new 
     { 
      app_id = (string)application.Attribute("app_id"), 
      app_name = (string)application.Attribute("app_name"), 
      app_AI = custom_field 

     }; 
+0

不應該'x.Attribute( 「名」)== 「必需」'是'x.Attribute( 「名稱」)值== 「必需」'? – barrick 2014-09-02 21:19:44

+0

我試了兩種。沒有運氣.. – mhn 2014-09-02 21:26:40

回答

0

看看這是否會工作。請注意,您可以將「元素」和其他一些擴展方法直接鏈接到IEnumerable<T>以使其更簡單。

from app in doc.Elements("appinfo").Elements("application") 
from cf in app.Elements("customfield") 
where (string)cf.Attribute("name") == "Required" 
select new 
{ 
    app_id = (string)app.Attribute("app_id"), 
    app_name = (string)app.Attribute("app_name"), 
    app_AI = (string)cf.Attribute("value") 
}; 

Descendants是很少有用的方法,因爲它可以隱藏你的文檔中潛在的結構性問題。除非我在其他地方執行驗證(如使用XSD),否則我不會使用它。

+0

它工作..與一個小的變化。 。對於我的新XML,它必須是doc.Root.Elements。此外,cf.Attribute(「value」)。Value!=「」條件被添加 – mhn 2014-09-02 22:47:16

1

這似乎爲我工作:

var results = 
    from appInfo in d.Elements() 
    let application = appInfo.Elements().First() 
    let custom_field = application.Descendants() 
     .Where(x => x.Attribute("name").Value == "Required" && x.Attribute("value").Value != "") 
     .SingleOrDefault() 
    select new 
    { 
     app_id = application.Attribute("app_id").Value, 
     app_name = application.Attribute("app_name").Value, 
     app_AI = custom_field.Attribute("value").Value 
    }; 

我覺得你的問題主要是看d.Root.Elements,而不是僅僅d.Elements

例:https://dotnetfiddle.net/XVM1qz

+0

我錯過了根標籤在我的問題。道歉..我試着用d.Root.Elements()。我得到的對象引用沒有設置錯誤 – mhn 2014-09-02 22:02:26

+0

奇怪..當我嘗試你的小提琴鏈接..即使在添加根後,它工作正常 – mhn 2014-09-02 22:05:05

+0

我發現了錯誤。這是因爲很少節點沒有應用程序的結束標記。在這裏複製了相同的https://dotnetfiddle.net/YUoL4N – mhn 2014-09-02 22:24:51