2009-02-11 63 views
3

我再次... 我有一個XML文件包含不同的類別,我想查詢不同的屬性。與AND運算符LINQ子查詢顯示沒有結果

 <item>  
      <title>Industries</title>  
      <category type="Channel">Automotive</category>  
      <category type="Type">Cars</category>  
      <category type="Token">Article</category>  
      <category type="SpecialToken">News</category>  
      <guid>637f0dd7-57a0-4001-8272-f0fba60feba1</guid> 
     </item> 

IN SQL我會寫類似的東西。

select * from articles where channel = 'Automative' AND type = 'Cars' etc. etc. 

我該怎麼用linq做到這一點? 我試過以下查詢,但它返回null。如果我將這兩個屬性與「OR」||相結合運算符我會得到結果,但如果一個項目符合兩個條件,則會得到所有雙重結果。

var articleList = (from item in doc.Descendants("item") 

         from _category in item.Elements("category") 
         where _category.Value == valueCboChannel && _category.Attribute("domain").Value == "Channel" 
         && (_category.Value == valueCboSubChannel && _category.Attribute("domain").Value == "SubChannel") 

         select new 
         { 

          Title = item.Element("title").Value, 
          Guid= item.Element("guid").Value, 
          description = item.Element("description").Value, 
          link = item.Element("link").Value 
         }).ToList(); 

      ListView1.DataSource = articleList; 
      ListView1.DataBind();    

回答

3

我與擴展方法簡化它做棘手的查找:

(更新09年12月2日,以排除空元素)

static string CategoryValue(this XElement element, string type) 
{ 
    var category = element.Elements("category").FirstOrDefault(
     c => (string)c.Attribute("type") == type 
      && !string.IsNullOrEmpty(c.Value)); // UPDATE HERE 
    return category == null ? null : category.Value; 
} 

static void Main() 
{ 
    XDocument doc = XDocument.Parse(xml); 
    var qry = from item in doc.Descendants("item") 
       where item.CategoryValue("Channel") == "Automotive" 
       && item.CategoryValue("Type") == "Cars" 
       select item; 
    foreach (var node in qry) 
    { 
     Console.WriteLine(node.Element("guid").Value); 
    } 
} 
+0

非常感謝馬克。現在起作用了。不知何故,我無法弄清楚isNullOrEmpty。 – Chris 2009-02-12 16:47:27

0

感謝您的提示,我以某種方式管理它,但只在擴展方法中使用「.First」。

我現在面臨的問題是如何獲取xml文件中存在NULL值的所有值。基本上這個xml可能如下所示。所以如果我使用「第一」,當然第一個空的將被選中,因此不顯示。 有沒有辦法跳過NULL值?

<item> 
    <title>Industries</title> 
    <category type="Channel"></category> 
    <category type="Channel">Automotive</category> 
    <category type="Type"></category>  
    <category type="Type">Cars</category>  
    <category type="Token">Article</category>  
    <category type="SpecialToken">News</category>  
    <guid>637f0dd7-57a0-4001-8272-f0fba60feba1</guid> 
</item> 

這裏當前的擴展方法

public static string CategoryValue(this XElement item, string type) 
    { 
     var category = item.Descendants("category").First(c => (string)c.Attribute("type") == type); 
     return category == null ? null : category.Value; 

    } 
+0

我會更新我以前的答案,以說明... – 2009-02-12 15:45:16