Robert
Robert

Reputation: 4406

How to check if an XML attribute contains a string?

Here is the XML (I have saved an html page in xml form to parse it generically:

<td width="76" class="DataB">2.276</td>
<td width="76" class="DataB">2.289</td>
<td width="76" class="DataB">2.091</td>
<td width="76" class="DataB">1.952</td>
<td width="76" class="DataB">1.936</td>
<td width="76" class="Current2">1.899</td>

Now I am trying to find all of the elements that contain the string Current because the web page changes the number on the back:

var xElements = xml.Descendants("td").Where(element => ((string) element.Attribute("class")).Contains("Current"));

This returns an object does not exist error here:

((string) element.Attribute("class"))

How can I check an attribute if it contains something?

Upvotes: 0

Views: 2509

Answers (2)

Jeff Mercado
Jeff Mercado

Reputation: 134491

If you asked me, it would be easier to write as an xpath query. This way you don't have to deal with cases where elements doesn't contain class attributes and other such cases.

var query = xml.XPathSelectElements("//td[contains(@class,'Current')]");

Otherwise, you would have to check for the existence of the attribute before trying to read it.

// query syntax makes this a little nicer
var query =
    from td in xml.Descendants("td")
    let classStr = (string)td.Attribute("class")
    where classStr != null && classStr.Contains("Current")
    select td;
// or alternatively, provide a default value
var query =
    from td in xml.Descendants("td")
    where ((string)td.Attribute("class") ?? "").Contains("Current")
    select td;

Upvotes: 4

Dan Field
Dan Field

Reputation: 21661

There's probably something wrong with the XML input you're using - trying this code works for me in LINQPad:

XDocument xml = XDocument.Parse(@"<tr><td width=""76"" class=""DataB"">2.276</td>
<td width=""76"" class=""DataB"">2.289</td>
<td width=""76"" class=""DataB"">2.091</td>
<td width=""76"" class=""DataB"">1.952</td>
<td width=""76"" class=""DataB"">1.936</td>
<td width=""76"" class=""Current2"">1.899</td></tr>");

var xElements = xml.Descendants("td").Where(element => ((string) element.Attribute("class")).Contains("Current"));

xElements.Dump();

Are you sure your XML is valid?

Upvotes: 0

Related Questions