2011-08-02 233 views
0

我有一個XML文件,我試圖通過屬性「寬度」進行分組。這裏是一個片段:需要LinqToXml分組幫助

<nodes> 
<FieldType Name="1000" OriginalName="1000" ScriptName="" SqlType="12" Width="1000" EnableValues="0" Scale="0" ForceMatch="0" ForceMatchCaseSensitive="0" SortAlphabetically="0" /> 
<FieldType Name="Varchar 1000" OriginalName="Varchar1000" ScriptName="" SqlType="12" Width="1000" EnableValues="0" Scale="0" ForceMatch="0" ForceMatchCaseSensitive="0" SortAlphabetically="0" /> 
<FieldType Name="Varchar 10001" OriginalName="Varchar1000" ScriptName="" SqlType="12" Width="1000" EnableValues="0" Scale="0" ForceMatch="0" ForceMatchCaseSensitive="0" SortAlphabetically="0" /> 
<FieldType Name="2000" OriginalName="1000" ScriptName="" SqlType="12" Width="200" EnableValues="0" Scale="0" ForceMatch="0" ForceMatchCaseSensitive="0" SortAlphabetically="0" /> 
<FieldType Name="Varchar 200" OriginalName="Varchar1000" ScriptName="" SqlType="12" Width="200" EnableValues="0" Scale="0" ForceMatch="0" ForceMatchCaseSensitive="0" SortAlphabetically="0" /> 
<FieldType Name="Varchar 2001" OriginalName="Varchar1000" ScriptName="" SqlType="12" Width="200" EnableValues="0" Scale="0" ForceMatch="0" ForceMatchCaseSensitive="0" SortAlphabetically="0" /> 
<FieldType Name="Y/N" ScriptName="" SqlType="12" Width="1" EnableValues="1" ForceMatch="1" Scale="0" ForceMatchCaseSensitive="0" SortAlphabetically="0" /> 

我希望我的解析返回2個值,1000和2000,因爲我想唯一的寬度。我寫的代碼是:

  XDocument xmlDoc = XDocument.Load(@"c:\temp\sample.xml"); 
     var q = from c in xmlDoc.Descendants("FieldType") 
       group xmlDoc by c.Attribute("Width") into cust_widths 
       select new 
       { 
        key = cust_widths.Key, 
        value = from val in cust_widths.Elements("Width") select (string)val 
       }; 

     foreach (var name in q) 
     { 
      System.Diagnostics.Debug.WriteLine(name); 
     } 

但仍然返回:1000,1000,1000,200,200,200

任何想法有什麼錯我的語法?

回答

4

試試這個:

XDocument xmlDoc = XDocument.Load(@"c:\temp\sample.xml"); 
var q = 
    from c in xmlDoc.Descendants("FieldType") 
    group c by c.Attribute("Width").Value into cust_widths 
    select cust_widths.Key; 

foreach (var name in q) 
{ 
    System.Diagnostics.Debug.WriteLine(name); 
} 

您的代碼有幾個問題:

  1. 你被分組整個xmlDoc中成集團,而不是僅僅的FieldType元素。
  2. 您正在按XAttribute對象進行分組,而不是按屬性值進行分組。

實際上,有查詢的一個更簡單的版本:

var q = xmlDoc 
    .Descendants("FieldType") 
    .Select(c => c.Attribute("Width").Value) 
    .Distinct(); 
+0

男人,我很接近!我想增加的價值使每一行都是唯一的。謝謝,我喜歡你更簡單的版本更好,要愛linq。 –

1

既然你由Attribute()符返回XAttribute對象分組,您將獲得獨特的按鍵組的每個單個元素。您需要使用返回屬性的Value屬性按屬性值進行分組。

+0

是的,我很近,很好! –