获取HTML元素的值

时间:2012-11-05 14:43:27

标签: c# regex

我在文本文件中有网页的HTML代码。我希望我的程序返回标记中的值。例如。我想得到" Julius"出于

<span class="hidden first">Julius</span>

我需要正则表达吗?否则什么是可以做到的字符串函数?

4 个答案:

答案 0 :(得分:10)

你应该使用像htmlagilitypack这样的html解析器.Regex不是解析HTML文件的好选择,因为HTML不严格,也不是常规的格式。

您可以使用以下代码使用HtmlAgilityPack

检索它
HtmlDocument doc = new HtmlDocument();
doc.Load(yourStream);

var itemList = doc.DocumentNode.SelectNodes("//span[@class='hidden first']")//this xpath selects all span tag having its class as hidden first
                  .Select(p => p.InnerText)
                  .ToList();

//itemList now contain all the span tags content having its class as hidden first

答案 1 :(得分:7)

我会使用Html Agility Pack来解析C#中的HTML。

答案 2 :(得分:2)

我强烈建议您查看类似HTML Agility Pack

的内容

答案 3 :(得分:1)

我几天前问了同样的问题,并且使用了HTML Agility Pack,但是这里是您想要的正则表达式

这个将忽略属性

<span[^>]*>(.*?)</span>

这个会考虑属性

<span class="hidden first"[^>]*>(.*?)</span>