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");
============
09/22/2007 更新:
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 "";
}
private string GetFixTagContent(string inputstring,string tagName)
{
string regleftTag = "<" + tagName + "[^<>]*>";
string rightTag="</"+tagName+">";
Regex reg = new Regex(regleftTag + "(.|/n)*" + rightTag, RegexOptions.IgnoreCase);
string result = reg.Match(inputstring.ToLower()).Value;
if (string.IsNullOrEmpty(result)) return "";
return Server.HtmlDecode(result.Replace(new Regex(regleftTag, RegexOptions.IgnoreCase).Match(result).ToString(), "").Replace(rightTag, ""));
}
来自:http://www.cnblogs.com/neilvension/archive/2007/09/13/993419.html