How to select nodes which contain a string in their class name with XPath in C#?

时间:2016-07-11 19:44:38

标签: c# html css xpath

I have span nodes with class atrribute like this:

<span class=" cite fw-xl fz-ms lh-17">www.azlyrics.com</span>
<span class=" fz-ms fw-m fc-12th wr-bw lh-17">www.imdb.com</span>

I want to access all of thes elements with thoes class property. I write this code but it returns null:

node.SelectSingleNode(".//span[contains(@class,'lh-17')]").InnerText;

How should I get both of these elements?

1 个答案:

答案 0 :(得分:1)

This should work for you

string XmlContent = "<span class=\" cite fw-xl fz-ms lh-17\">www.azlyrics.com</span><span class=\" fz-ms fw-m fc-12th wr-bw lh-17\">www.imdb.com</span>";

XmlDocument doc = new XmlDocument();
doc.LoadXml("<root>" + XmlContent + "</root>");
XmlNode newNode = doc.DocumentElement;
XmlNodeList ab = newNode.SelectNodes("//span[contains(@class, 'lh-17')]");

foreach (XmlNode k in ab)
{
   Console.WriteLine(k.InnerText);
}