Sunday, January 22, 2012

LINQ to XML (XHTML)

The blog is going to be more code based from now on. I'll probably still post some art here and there, however, personally I'm focusing on my programming. Anyhow, here's some LINQ to XML extension methods I'm working on. I write my LINQ with lambda expressions. These are in context of querying for HTML elements, so I'm guessing their use will be limiting for most.


https://github.com/joeyshipley/LINQ-to-xml-extension-methods


var htmlElement = xdoc.Descendants()
 .FirstOrDefault(d => d.Attribute("class") != null && d.Attribute("class").Value.ToLower().Contains(searchingForClassNameVariable.ToLower()));
var htmlElementValue = htmlElement != null
 ? htmlElement.Value.Trim()
 : string.Empty;

With the extension methods, I'm now writting the above code as:

var htmlElementValue = xdoc.Descendants()
 .FirstOrDefaultByAttribute("class", searchingForClassNameVariable)
 .ElementValue();

Sorry about the formatting, I'll find my code formatting and put it back on the blog. In the somewhat near future.