/// <summary> /// 创建选择器 /// </summary> /// <param name="expression">选择器表达式</param> /// <returns>选择器实例</returns> public static ICssSelector Create(string expression) { if (selectorCache.ContainsKey(expression)) { return(selectorCache[expression]); } var match = casecadingSelectorRegex.Match(expression); if (!match.Success) { throw new FormatException(); } ICssSelector selector = CssElementSelector.Create(match.Groups["leftSelector"].Value); foreach (var extraCapture in match.Groups["extra"].Captures.Cast <Capture>()) { var relative = extraCapture.FindCaptures(match.Groups["relative"]).Single().Value.Trim(); var rightSelector = extraCapture.FindCaptures(match.Groups["rightSelector"]).Single().Value.Trim(); selector = new CssCasecadingSelector(selector, relative, CssElementSelector.Create(rightSelector)); } lock ( _cacheSync ) { selectorCache[expression] = selector; } return(selector); }
/// <summary> /// 获取符合条件的子元素 /// </summary> /// <param name="container">要获取子元素的容器</param> /// <param name="selector">用来筛选子元素的元素选择器</param> /// <returns>符合条件的子元素</returns> public static IEnumerable <IHtmlElement> Elements(this IHtmlContainer container, string selector) { if (container == null) { throw new ArgumentNullException("container"); } if (selector == null) { throw new ArgumentNullException("selector"); } return(CssElementSelector.Create(selector).Filter(Elements(container))); }
/// <summary> /// 获取符合条件的兄弟(同级)元素节点 /// </summary> /// <param name="node">要获取兄弟(同级)元素节点的节点</param> /// <param name="selector">用于筛选元素的元素选择器</param> /// <returns>所有的兄弟(同级)元素节点</returns> public static IEnumerable <IHtmlElement> Siblings(this IHtmlNode node, string selector) { return(CssElementSelector.Create(selector).Filter(node.Siblings())); }
/// <summary> /// 获取符合条件的父代元素 /// </summary> /// <param name="node">要获取父代元素集合的节点</param> /// <param name="selector">用来筛选父代元素的元素选择器</param> /// <returns>节点的所有父代元素集合</returns> public static IEnumerable <IHtmlElement> Ancestors(this IHtmlNode node, string selector) { return(CssElementSelector.Create(selector).Filter(Ancestors(node))); }