DooDoo
DooDoo

Reputation: 13487

get Node by it's attribute in linq to xml

consider this HTML:

<table>
  <tr>
    <td width="45%" align="right">
      <h2>1.00 NZD</h2>
    </td> 
    <td valign="top" align="center">
      <h2>=</h2>
    </td> 
    <td width="45%" align="left">
      <h2>0.415528 GBP</h2>
    </td>
  </tr>
</table>

I use this code as string and convert it to a XML file:

string raw = "<table><tr><td width=\"45%\" align=\"right\"><h2>1.00 NZD</h2></td><td valign=\"top\" align=\"center\"><h2>=</h2></td><td width=\"45%\" align=\"left\"> <h2>0.415528 GBP</h2> </td></tr></table>";

XElement info = XElement.Parse(raw);

now I want to get All td that have align="right" and write this code:

var elementToChange = (from c in info.Elements("td")
                            where c.Attribute("align").Value == "right"
                            select c);


 Label1.Text = Server.HtmlEncode(elementToChange.First().ToString());

but I get this Error:

Sequence contains no elements

where is problem?

thanks

Upvotes: 2

Views: 370

Answers (2)

Botz3000
Botz3000

Reputation: 39650

You look for "td" elements but at the top level of the node you only find a "tr" element. That's why you don't get any elements. Try this:

from c in info.Elements("tr").Elements("td")

Also, you should check if there are any elements in the sequence before calling First() (or use FirstOrDefault() which returns null if there is no element).

If you don't know the path and only want all "td" elements with that tag value, you can also use the Descendants extension method:

from c in info.Descendants("td")

Upvotes: 3

Konstantin Dinev
Konstantin Dinev

Reputation: 34915

Elements would give you the immediate child elements of the root in this case info. You need to drill down to the elements you are looking for and then extract them by the Where clause. In your case the immediate children are the <tr>s.

Upvotes: 0

Related Questions