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:
Your code had a few issues:
FieldTypeelements.XAttributeobjects instead of by the attributes’ values.There’s actually an even simpler version of the query: