CsQuery获取IDomObject元素的完整CSS选择器
一、方法说明
通过IDomObject元素,获取完整的CSS选择器,过滤HTML和BODY元素,自动将class、id添加到选择器上,优先添加class,无class再添加id。如:
<html> <head></head> <body> <div id="result"> <h3 class="t"><a "="" href="http://www.baidu.com/link?url=PgEyrxusTKZjg64DFOd_qlTy4o7dXLH_26WOy1mg6JUwVE4L_KrH24eG7s49yN8R-iBqQEb80m2gLmAzab8FIK&ck=4276.4.1526360648567.0.0.250.568.0&shh=www.baidu.com&sht=baidu" target="_blank">CSS教程</a></h3> </div> </body> </html>
a元素的完整的CSS选择器为:DIV#result H3.t A
二、方法实现
public string GetFullCssSelector(IDomObject dom) { string str = ""; while (dom != null && dom.NodeName != null) { string nodeName = dom.NodeName; if (!(new[] {"HTML", "BODY"}.Contains(nodeName))) //过滤HTML、BODY { if (dom.HasAttribute("class")) { string s = dom.Attributes["class"]; s = s.Replace(" ", " ").Replace(" ", " ").Replace(" ", " "); string[] strings = s.Split(' '); foreach (string str2 in strings) { nodeName += "." + str2; } } else if (dom.HasAttribute("id")) { nodeName += "#" + dom.Attributes["id"]; } str = nodeName + " " + str; } dom = dom.ParentNode; } return str.Trim(); }
--版权信息--
转载请标明文章出处,谢谢!
文章作者:易几 http://www.cnblogs.com/InfoStudio/
--版权信息--