forked from szgit/Helper.Core.Library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HtmlAnalysisHelper.cs
372 lines (337 loc) · 16.2 KB
/
HtmlAnalysisHelper.cs
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
/*
* 作用:通过 HtmlAgilityPack 和 XPath 实现 Html 数据解析。
* 联系:QQ 100101392
* 来源:https://github.com/snipen/Helper.Core.Library
* */
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Helper.Core.Library
{
#region 逻辑处理辅助枚举
public enum HtmlAnalysisEnum
{
/// <summary>
/// 严格模式
/// </summary>
Strict = 1,
/// <summary>
/// 非严格模式
/// </summary>
Normal = 2
}
#endregion
public class HtmlAnalysisHelper
{
#region 对外公开方法
/// <summary>
/// 获取标题
/// </summary>
/// <param name="htmlDocument">HtmlDocument</param>
/// <returns></returns>
public static string GetTitle(HtmlDocument htmlDocument)
{
return ToT<string>(htmlDocument, "//title", null, HtmlAnalysisAttributeEnum.Text);
}
/// <summary>
/// 获取内容
/// </summary>
/// <typeparam name="T">基类类型,例:string</typeparam>
/// <param name="htmlDocument">HtmlDocument</param>
/// <param name="xPath">XPath 查询语句</param>
/// <param name="attributeName">属性名称</param>
/// <param name="attributeEnum">属性枚举</param>
/// <returns></returns>
public static T ToT<T>(HtmlDocument htmlDocument, string xPath, string attributeName, HtmlAnalysisAttributeEnum attributeEnum = HtmlAnalysisAttributeEnum.Attribute)
{
T t = default(T);
HtmlNode documentNode = htmlDocument.DocumentNode;
if (documentNode == null) return t;
HtmlNode htmlNode = documentNode.SelectSingleNode(xPath);
if (htmlNode == null) return t;
string attributeValue = GetNodeText(htmlNode, attributeName, attributeEnum);
if (string.IsNullOrEmpty(attributeValue)) return t;
t = (T)Convert.ChangeType(attributeValue, typeof(T));
return t;
}
/// <summary>
/// 返回实体数据列表
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="analysisEnum">解析模式</param>
/// <param name="htmlDocument">HtmlDocument</param>
/// <param name="xPath">XPath 查询语句</param>
/// <param name="xPathMatchList">属性 XPath 查询语句列表</param>
/// <param name="propertyMatchList">属性匹配,Dictionary<string, object> 或 new {}</param>
/// <param name="reflectionType">反射类型</param>
/// <returns></returns>
public static List<T> ToEntityList<T>(HtmlAnalysisEnum analysisEnum, HtmlDocument htmlDocument, string xPath, List<XPathMatch> xPathMatchList = null, object propertyMatchList = null, ReflectionTypeEnum reflectionType = ReflectionTypeEnum.Expression) where T : class, new()
{
if (analysisEnum == HtmlAnalysisEnum.Strict)
{
return ToEntityListStrict<T>(htmlDocument, xPath, xPathMatchList, propertyMatchList, reflectionType);
}
else
{
return ToEntityListNormal<T>(htmlDocument, xPath, xPathMatchList, propertyMatchList, reflectionType);
}
}
/// <summary>
/// 返回实体数据列表
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="analysisEnum">解析模式</param>
/// <param name="htmlDocument">HtmlDocument</param>
/// <param name="xPath">XPath 查询语句</param>
/// <param name="xPathMatchDict">属性 XPath 查询语句字典</param>
/// <param name="propertyMatchList">属性匹配,Dictionary<string, object> 或 new {}</param>
/// <param name="reflectionType">反射类型</param>
/// <returns></returns>
public static List<T> ToEntityList<T>(HtmlAnalysisEnum analysisEnum, HtmlDocument htmlDocument, string xPath, Dictionary<string, string> xPathMatchDict, object propertyMatchList = null, ReflectionTypeEnum reflectionType = ReflectionTypeEnum.Expression) where T : class, new()
{
List<XPathMatch> xPathMatchList = new List<XPathMatch>();
foreach(var keyValueItem in xPathMatchDict)
{
xPathMatchList.Add(new XPathMatch() { PropertyName = keyValueItem.Key, XPath = keyValueItem.Value });
}
return ToEntityList<T>(analysisEnum, htmlDocument, xPath, xPathMatchList, propertyMatchList, reflectionType);
}
/// <summary>
/// 返回基础类型数据列表
/// </summary>
/// <typeparam name="T">基类类型,例:string</typeparam>
/// <param name="htmlDocument">HtmlDocument</param>
/// <param name="xPath">XPath 查询语句</param>
/// <param name="attributeName">属性名称</param>
/// <param name="attributeEnum">属性枚举</param>
/// <returns></returns>
public static List<T> ToList<T>(HtmlDocument htmlDocument, string xPath, string attributeName, HtmlAnalysisAttributeEnum attributeEnum = HtmlAnalysisAttributeEnum.Attribute)
{
HtmlNode documentNode = htmlDocument.DocumentNode;
if (documentNode == null) return null;
List<T> dataList = new List<T>();
HtmlNodeCollection htmlNodeCollection = documentNode.SelectNodes(xPath);
if (htmlNodeCollection == null || htmlNodeCollection.Count == 0) return null;
foreach(HtmlNode htmlNode in htmlNodeCollection)
{
string attributeValue = GetNodeText(htmlNode, attributeName, attributeEnum);
if (!string.IsNullOrEmpty(attributeValue))
{
dataList.Add((T)Convert.ChangeType(attributeValue, typeof(T)));
}
}
return dataList;
}
#endregion
#region 逻辑处理私有函数
private static List<T> ToEntityListStrict<T>(HtmlDocument htmlDocument, string xPath, List<XPathMatch> xPathMatchList = null, object propertyMatchList = null, ReflectionTypeEnum reflectionType = ReflectionTypeEnum.Expression) where T : class, new()
{
HtmlNode documentNode = htmlDocument.DocumentNode;
if (documentNode == null) return null;
List<T> dataList = new List<T>();
HtmlNodeCollection htmlNodeCollection = documentNode.SelectNodes(xPath);
if (htmlNodeCollection == null || htmlNodeCollection.Count == 0) return null;
Dictionary<string, List<HtmlNode>> propertyNodeDict = GetXPathNodeDict(documentNode, xPathMatchList, htmlNodeCollection.Count);
dynamic propertySetDict = null;
if (reflectionType != ReflectionTypeEnum.Original) propertySetDict = ReflectionExtendHelper.PropertySetCallDict<T>(reflectionType);
Dictionary<PropertyInfo, HtmlAttributeMapperItem> attributeMapperDict = GetAttributeMapperDict<T>(propertyMatchList);
int index = 0;
foreach (HtmlNode mathHtmlNode in htmlNodeCollection)
{
dataList.Add(HtmlNodeToEntity<T>(mathHtmlNode, index, propertyNodeDict, propertySetDict, attributeMapperDict));
index++;
}
return dataList;
}
private static List<T> ToEntityListNormal<T>(HtmlDocument htmlDocument, string xPath, List<XPathMatch> xPathMatchList = null, object propertyMatchList = null, ReflectionTypeEnum reflectionType = ReflectionTypeEnum.Expression) where T : class, new()
{
HtmlNode documentNode = htmlDocument.DocumentNode;
if (documentNode == null) return null;
List<T> dataList = new List<T>();
dynamic propertySetDict = null;
if (reflectionType != ReflectionTypeEnum.Original) propertySetDict = ReflectionExtendHelper.PropertySetCallDict<T>(reflectionType);
Dictionary<PropertyInfo, HtmlAttributeMapperItem> attributeMapperDict = GetAttributeMapperDict<T>(propertyMatchList);
HtmlNodeCollection htmlNodeCollection = documentNode.SelectNodes(xPath);
if (htmlNodeCollection == null || htmlNodeCollection.Count == 0) return null;
Dictionary<PropertyInfo, XPathMatch> propertyInfoXPathDict = new Dictionary<PropertyInfo, XPathMatch>();
XPathMatch matchItem = null;
foreach (HtmlNode htmlNode in htmlNodeCollection)
{
T t = new T();
ReflectionGenericHelper.Foreach<T>((PropertyInfo propertyInfo) =>
{
matchItem = null;
if (propertyInfoXPathDict.ContainsKey(propertyInfo))
{
matchItem = propertyInfoXPathDict[propertyInfo];
}
else
{
matchItem = xPathMatchList.Where(p => p.PropertyName == propertyInfo.Name).FirstOrDefault();
if (matchItem != null) propertyInfoXPathDict.Add(propertyInfo, matchItem);
}
if (matchItem != null)
{
HtmlNode childHtmlNode = htmlNode.SelectSingleNode(matchItem.XPath);
SetEntityValue<T>(t, childHtmlNode, propertyInfo, attributeMapperDict[propertyInfo], propertySetDict);
}
});
dataList.Add(t);
}
return dataList;
}
private static T HtmlNodeToEntity<T>(HtmlNode htmlNode, int index, Dictionary<string, List<HtmlNode>> nodeDict, dynamic propertySetDict, Dictionary<PropertyInfo, HtmlAttributeMapperItem> attributeMapperDict) where T : class, new()
{
T t = ReflectionGenericHelper.New<T>();
HtmlNode dataNode = htmlNode;
foreach (var keyValueItem in attributeMapperDict)
{
if (nodeDict != null && nodeDict.ContainsKey(keyValueItem.Key.Name))
{
dataNode = nodeDict[keyValueItem.Key.Name][index];
}
string attributeValue = GetNodeText(dataNode, keyValueItem.Value.AttributeName, keyValueItem.Value.AttributeEnum);
if (!string.IsNullOrEmpty(attributeValue))
{
if (propertySetDict != null && propertySetDict.ContainsKey(keyValueItem.Key.Name))
{
ReflectionGenericHelper.SetPropertyValue(propertySetDict[keyValueItem.Key.Name], t, attributeValue, keyValueItem.Key);
}
else
{
ReflectionHelper.SetPropertyValue(t, attributeValue, keyValueItem.Key);
}
}
}
return t;
}
private static void SetEntityValue<T>(T t, HtmlNode htmlNode, PropertyInfo propertyInfo, HtmlAttributeMapperItem mapperItem, dynamic propertySetDict) where T : class
{
string attributeValue = GetNodeText(htmlNode, mapperItem.AttributeName, mapperItem.AttributeEnum);
if (!string.IsNullOrEmpty(attributeValue))
{
if (propertySetDict != null && propertySetDict.ContainsKey(propertyInfo.Name))
{
ReflectionGenericHelper.SetPropertyValue(propertySetDict[propertyInfo.Name], t, attributeValue, propertyInfo);
}
else
{
ReflectionHelper.SetPropertyValue(t, attributeValue, propertyInfo);
}
}
}
private static Dictionary<string, List<HtmlNode>> GetXPathNodeDict(HtmlNode htmlNode, List<XPathMatch> xPathMatchList, int nodeCount)
{
Dictionary<string, List<HtmlNode>> nodeDict = new Dictionary<string, List<HtmlNode>>();
foreach(XPathMatch matchItem in xPathMatchList)
{
HtmlNodeCollection htmlNodeList = htmlNode.SelectNodes(matchItem.XPath);
if(htmlNodeList != null && htmlNodeList.Count == nodeCount)
{
nodeDict.Add(matchItem.PropertyName, htmlNodeList.ToList());
}
}
return nodeDict;
}
private static Dictionary<PropertyInfo, HtmlAttributeMapperItem> GetAttributeMapperDict<T>(object propertyMatchList) where T : class
{
Dictionary<string, object> propertyMatchDict = CommonHelper.GetParameterDict(propertyMatchList);
Dictionary<PropertyInfo, HtmlAttributeMapperItem> propertyDict = new Dictionary<PropertyInfo, HtmlAttributeMapperItem>();
ReflectionGenericHelper.Foreach<T>((PropertyInfo propertyInfo) =>
{
HtmlAttributeMapperItem mapperItem = new HtmlAttributeMapperItem();
if (propertyMatchDict != null && propertyMatchDict.ContainsKey(propertyInfo.Name))
{
mapperItem.AttributeName = propertyMatchDict[propertyInfo.Name].ToString();
mapperItem.AttributeEnum = HtmlAnalysisAttributeEnum.Attribute;
}
else
{
HtmlAnalysisTAttribute attribute = propertyInfo.GetCustomAttribute<HtmlAnalysisTAttribute>();
if (attribute != null)
{
mapperItem.AttributeName = attribute.Name;
mapperItem.AttributeEnum = attribute.NameType;
}
else
{
mapperItem.AttributeName = propertyInfo.Name;
mapperItem.AttributeEnum = HtmlAnalysisAttributeEnum.Attribute;
}
}
propertyDict.Add(propertyInfo, mapperItem);
});
return propertyDict;
}
private static string GetNodeText(HtmlNode htmlNode, string attributeName, HtmlAnalysisAttributeEnum attributeEnum)
{
if (htmlNode == null) return null;
if (attributeEnum == HtmlAnalysisAttributeEnum.Text) return htmlNode.InnerText;
if (attributeEnum == HtmlAnalysisAttributeEnum.Html) return htmlNode.InnerHtml;
if (htmlNode.Attributes[attributeName] == null) return null;
return htmlNode.Attributes[attributeName].Value;
}
#endregion
}
#region 逻辑处理辅助特性
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class HtmlAnalysisTAttribute : Attribute
{
private string name;
private HtmlAnalysisAttributeEnum nameType;
/// <summary>
/// 实体属性映射 Attribute 名称
/// </summary>
/// <param name="name">属性所对应的 Attribute 名称</param>
/// <param name="nameType">属性枚举</param>
public HtmlAnalysisTAttribute(string name, HtmlAnalysisAttributeEnum nameType = HtmlAnalysisAttributeEnum.Attribute)
{
this.name = name;
this.nameType = nameType;
}
/// <summary>
/// 实体属性所对应的 Attribute 名称
/// </summary>
public string Name { get { return this.name; } }
/// <summary>
/// 属性枚举
/// </summary>
public HtmlAnalysisAttributeEnum NameType { get { return this.nameType; } }
}
public enum HtmlAnalysisAttributeEnum
{
/// <summary>
/// 属性值
/// </summary>
Attribute = 0,
/// <summary>
/// InnerText 数据
/// </summary>
Text = 1,
/// <summary>
/// InnerHtml 数据
/// </summary>
Html = 2
}
#endregion
#region 逻辑处理辅助类
internal class HtmlAttributeMapperItem
{
public string AttributeName { get; set; }
public HtmlAnalysisAttributeEnum AttributeEnum { get; set; }
}
public class XPathMatch
{
/// <summary>
/// 属性名称
/// </summary>
public string PropertyName { get; set; }
/// <summary>
/// XPath
/// </summary>
public string XPath { get; set; }
}
#endregion
}