Denis
Denis

Reputation: 3759

Find elements by attribute name and its value using XDocument

Well, using .NET 3.5 and XDocument I am trying to find <table class='imgcr'> element. I created the code below but it crashes, of course, because e.Attribute("class") may be null. So... I have to put null check everywhere? This will double e.Attribute("class"). Not laconic solution at all.

XElement table =
    d.Descendants("table").
    SingleOrDefault(e => e.Attribute("class").Value == "imgcr");

Upvotes: 2

Views: 4106

Answers (2)

ocuenca
ocuenca

Reputation: 39386

If you are sure you exception is thrown because you table element may come without class attribute, then you could do this instead:

XElement table =
    d.Descendants("table").
    SingleOrDefault(e => ((string)e.Attribute("class")) == "imgcr");

In that case you are casting a null value to string, which is null at the end, so you are comparing null == "imgcr", what is false.

You can check this msdn page if you need more info about how to retrieve the value of an attribute. There you will find this affirmation:

You can cast an XAttribute to the desired type; the explicit conversion operator then converts the contents of the element or attribute to the specified type.

Upvotes: 3

Hogan
Hogan

Reputation: 70528

I guess this is quite short

XElement table =
  d.Descendants("table").
    SingleOrDefault(e => { var x = e.Attribute("class"); return x==null ? false: x.Value == "imgcr";});

this is shorter (but not much -- unless you can re-use t variable.)

XAttribute t = new XAttribute("class","");
XElement table =
  d.Descendants("table").
    SingleOrDefault(e => (e.Attribute("class") ?? t).Value == "imgcr");

Upvotes: 0

Related Questions