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
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:Also, you should check if there are any elements in the sequence before calling
First()(or useFirstOrDefault()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 theDescendantsextension method: