-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHtmlElementExtensions.cs
More file actions
66 lines (50 loc) · 1.88 KB
/
HtmlElementExtensions.cs
File metadata and controls
66 lines (50 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HtmlSerializer
{
public static class HtmlElementExtensions
{
public static bool Matches(this HtmlElement el, Selector sel)
{
if (sel == null) return false;
if (!string.IsNullOrEmpty(sel.TagName) &&
!string.Equals(el.Name, sel.TagName, StringComparison.OrdinalIgnoreCase))
return false;
if (!string.IsNullOrEmpty(sel.Id) &&
!string.Equals(el.Id, sel.Id, StringComparison.Ordinal))
return false;
if (sel.Classes != null && sel.Classes.Count > 0)
{
foreach (var cls in sel.Classes)
if (!el.Classes.Contains(cls)) return false;
}
return true;
}
public static List<HtmlElement> Query(this HtmlElement root, Selector selector)
{
if (root == null || selector == null)
return new List<HtmlElement>();
var results = new HashSet<HtmlElement>();
QueryRecursive(root, selector, results);
return results.ToList();
}
private static void QueryRecursive(HtmlElement context, Selector sel, HashSet<HtmlElement> acc)
{
if (context == null || sel == null) return;
// קבלת כל הצאצאים של context (ללא עצמו)
var candidates = context.Descendants().Where(e => e != context);
var matchedHere = candidates.Where(e => e.Matches(sel));
if (sel.Child == null)
{
foreach (var m in matchedHere)
acc.Add(m);
return;
}
foreach (var m in matchedHere)
QueryRecursive(m, sel.Child, acc);
}
}
}