【问题标题】:How to select nodes which contain a string in their class name with XPath in C#?如何在 C# 中使用 XPath 选择类名中包含字符串的节点?
【发布时间】:2019-04-02 02:33:09
【问题描述】:

我有像这样的类属性的跨度节点:

<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>

我想使用 thes 类属性访问所有这些元素。我写了这段代码,但它返回null:

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

我应该如何获得这两个元素?

【问题讨论】:

标签: c# html css xpath


【解决方案1】:

这应该适合你

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);
}

【讨论】:

  • tnx.但我不只是这两个跨度标签这是作为一个例子。我有一个 html 页面并加载它。然后就在 foreach node.SelectSingleNode(".//span[contains(@class,'lh-17')]").InnerText; 返回 NULL 而我有 10 个包含 'lh-17' 的跨度标签。
  • 这个解决方案中是否有多个跨度并不重要。只需将它们加载到 XmlContent 字符串变量中,并记住您必须使用 SelectNodes 而不是 SelectSingleNode
猜你喜欢
  • 2021-04-27
  • 1970-01-01
  • 2021-11-15
  • 1970-01-01
  • 2015-01-15
  • 1970-01-01
  • 1970-01-01
  • 2020-01-20
  • 1970-01-01
相关资源
最近更新 更多