Fremus.co.za

Demistifying Life and Web Development

Getting a single XAttribute or XElement

I have come across two ways querying XElements or XAttributes:

  • Make an object IEnumerable and loop through the results
  • Use the Single() method to return a single object only

Typically you may have a situation where you write some Linq-to-XML like this:

IEnumerable attrib = from att in elemInner.Attributes()
                                             where (string)att.Name.ToString() == "sectionName"
                                             select att;

To loop through the results you have to use a foreach loop like this:


foreach (XAttribute innerAttrib in attrib)
{
     builder.AppendLine("

" + innerAttrib.Value +"

"); }

If however you just wanted a single attribute result, you could write the same code like this:


 XAttribute attribDisplayStyle = (from att in elemInner.Attributes()
                                            where (string)att.Name.ToString() == "sectionName"
                                            select att).Single();

Then you only have a single XAttribute instance and you dont need a foreach loop:


attribDisplayStyle.Value;

You would apply the same logic to XElement as well.

  • Share/Bookmark
posted by fr3dr1k in C#,LINQ to XML and have No Comments
Get Adobe Flash playerPlugin by wpburn.com wordpress themes