吴旭晓个人博客 繁体中文 简体中文

首页| 日志 |JAVA |ASP |PHP |Android |IOS |ASP.NET |JavaScript |DIV+CSS |SEO |taobaoke |饼哥语录
繁体中文 简体中文

.NET获取Html字符串中指定标签的指定属性的值

using System.Text;
using System.Text.RegularExpressions;
以上为要用到的命名空间


    /// <summary>
    /// 获取Html字符串中指定标签的指定属性的值
    /// </summary>
    /// <param name="html">Html字符</param>
    /// <param name="tag">指定标签名</param>
    /// <param name="attr">指定属性名</param>
    /// <returns></returns>
    private List<string> GetHtmlAttr(string html, string tag, string attr)
    {

        Regex re = new Regex(@"(<" + tag + @"[\w\W].+?>)");
        MatchCollection imgreg = re.Matches(html);
        List<string> m_Attributes = new List<string>();
        Regex attrReg = new Regex(@"([a-zA-Z1-9_-]+)\s*=\s*(\x27|\x22)([^\x27\x22]*)(\x27|\x22)", RegexOptions.IgnoreCase);

        for (int i = 0; i < imgreg.Count; i++)
        {
            MatchCollection matchs = attrReg.Matches(imgreg[i].ToString());

            for (int j = 0; j < matchs.Count; j++)
            {
                GroupCollection groups = matchs[j].Groups;

                if (attr.ToUpper() == groups[1].Value.ToUpper())
                {
                    m_Attributes.Add(groups[3].Value);
                    break;
                }
            }

        }

        return m_Attributes;

    }

作者:吴旭晓 | 来源:个人博客 | 点击量:2123 | 发布时间:2013-06-22
最新留言 | 返回上一页 | 返回首页

相关文章:

版权所有:吴旭晓个人博客 Copyright © 2013-2023 个人博客