网站开发技术手记-读取html标签内容

1。读取单标签内容:

private string GetSingleTagValueByAttr(string inputstring,string tagName,string attrname,string key)

{

Regex reg = new Regex("<" + tagName + " [^<>]*>",RegexOptions.IgnoreCase);

MatchCollection matchs = reg.Matches(inputstring);

string result = "";

foreach (Match match in matchs)

{

string matchValue = match.Value;

Regex regValue = new Regex("content=\".*\"",RegexOptions.IgnoreCase);

if (matchValue.ToLower().IndexOf(attrname + "=\"" + key + "\"") != -1)

{

if(regValue.IsMatch(matchValue))

{

result = regValue.Match(matchValue).Value;

if (!string.IsNullOrEmpty(result))

{

result =result.ToLower().Replace("content=","").Replace("\"","");

}

}

return result;

}

}

return "";

}

使用举例:

string description=GetSingleTagValueByAttr(sourceHTML,“meta”,"name","description");

string keywords =GetSingleTagValueByAttr(sourceHTML,“meta”,"name","keywords");

改进:添加读取属性参数,目前只限定了读取的是meta的congtent的内容。

2。读取封闭标签的内容:

private string GetFixTagContent(string inputstring,string tagName)

{

string leftTag = "<" + tagName + ">";

string rightTag="</"+tagName+">";

Regex reg = new Regex("<" +tagName+"[^<>]*>(.|\n)*" + rightTag,RegexOptions.IgnoreCase);

return reg.Match(inputstring).Value.Replace(leftTag, "").Replace(rightTag, "");

}

使用举例:

string title=GetFixTagContent(sourceHTML,"title");