Need help with LinqToXml grouping
I have a XML file that I'm trying to group by the attribute "Width". Here is a snippet:
<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" />
I want my parse to return 2 values, 1000 and 2000 since I want the unique widths. The code I wrote is:
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);
}
But that still returns: 1000, 1000, 1000, 200, 200, 200.
Any idea what's wrong with my syntax?
Try this:
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);
}
Your code had a few issues:
- You were grouping the entire xmlDoc into the groupings instead of just the
FieldType
elements. - You were grouping by
XAttribute
objects instead of by the attributes' values.
There's actually an even simpler version of the query:
var q = xmlDoc
.Descendants("FieldType")
.Select(c => c.Attribute("Width").Value)
.Distinct();
Since you're grouping by the XAttribute
object returned by the Attribute()
operator, you're getting unique group keys for each single element. You need to use the Value
property of the returned attribute to group by the attribute value.
精彩评论