Wednesday, 15 May 2013

c# - How to check if an XML attribute contains a string? -


Here's the XML (I've saved an HTML page to parse it normally in XML form:

& lt; td width = "76" class = "DataB"> 2.276 & lt; / td> & lt; td width = "76" square = "databi" & gt; 2.289 & lt; / td & gt; & lt; td width = "76" class = "datab" & gt; 2.091 & lt; / td & gt; & lt; td width = "76" square = "database" & Gt; 1.952 & lt; / td & gt; & lt; td width = "76" class = "datab" & gt; 1.936 & lt; / td & gt; & lt; td width = "76" square = "current 2 "& gt; 1.899 & lt; / td>

Now I am trying to find all the elements The string in which the string is turned on because the web page changes the number on the back:

  var xElements = xml.Descendants ("td"). Where (element => (string) element attribute (" Class ")) (" current "));  

This returns an object error is not here:

 (string) element.Attribute ("class")) < / Code> 

How can I see a feature if there is something in it?

If you asked me, it would be easy to write in the form of a xpath query. In this way you do not have to deal with cases where the element does not include class attributes and other such cases.

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

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

  // Query syntax creates this small good type in Query = from xml.Descendants ("TD") classStr = (string) td.Attribute ("class") where classStr! = Null & amp; Amp; Select ClassStr.Contains ("Current") TD; // Or alternatively, xml.Descendants ("td") provides a default value var query = where td ("strings" td.Attribute ("class") "?" "") From td. In it selects ("current") td;  

No comments:

Post a Comment