forked from cyq1162/cyqdata
-
Notifications
You must be signed in to change notification settings - Fork 0
/
XHtmlBase.cs
597 lines (583 loc) · 19.1 KB
/
XHtmlBase.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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
using System;
using System.Xml;
using CYQ.Data.Cache;
using System.IO;
using System.Threading;
using System.Collections.Generic;
using System.Text;
using CYQ.Data.Table;
using System.Text.RegularExpressions;
using CYQ.Data.Tool;
namespace CYQ.Data.Xml
{
/// <summary>
/// 操作Xml及XHtml的基类
/// </summary>
public abstract class XHtmlBase : IDisposable
{
private Encoding _Encoding = Encoding.UTF8;
/// <summary>
/// 文件编码
/// </summary>
public Encoding Encoding
{
get
{
return _Encoding;
}
set
{
_Encoding = value;
}
}
/// <summary>
/// 用于批量赋值(LoadData(MDataRow,pre)方法装载)
/// </summary>
protected List<string> PreList;
/// <summary>
/// xml对象
/// </summary>
protected XmlDocument _XmlDocument;
/// <summary>
/// 内部XmlDocument对象(ReadOnly)
/// </summary>
public XmlDocument XmlDoc
{
get
{
return _XmlDocument;
}
}
/// <summary>
/// 命名空间对象
/// </summary>
protected XmlNamespaceManager xnm;
/// <summary>
/// 缓存对象
/// </summary>
protected CacheManage theCache;
/// <summary>
/// Html名称空间
/// </summary>
protected string htmlNameSpace = "http://www.w3.org/1999/xhtml";
internal string PreXml = "preXml";
/// <summary>
/// 加载的Xml文件的完整(路径)名称(ReadOnly)
/// </summary>
public string FileName
{
get
{
return _FileName;
}
}
private string _FileName = string.Empty;
/// <summary>
/// xml缓存的key
/// </summary>
public string XmlCacheKey = string.Empty;
private bool _IsNoClone;
/// <summary>
/// 存取档不克隆(此时XHtml应是只读模式)
/// </summary>
public bool IsNoClone
{
get
{
return _IsNoClone;
}
set
{
_IsNoClone = value;
}
}
private bool _IsLoadFromCache;
/// <summary>
/// 文档是否取自缓存
/// </summary>
public bool IsLoadFromCache
{
get
{
return _IsLoadFromCache;
}
set
{
_IsLoadFromCache = value;
}
}
private double _CacheMinutes = 5;
/// <summary>
/// 缓存分钟数(ReadOnly)
/// </summary>
public double CacheMinutes
{
get
{
return _CacheMinutes;
}
}
/// <summary>
/// 返回最终格式化后的XHtml内容(ReadOnly)
/// </summary>
public virtual string OutXml
{
get
{
return _XmlDocument.OuterXml;
}
}
/// <summary>
/// 加载的Html是否已改变(ReadOnly)
/// </summary>
public bool IsXHtmlChanged
{
get
{
return !theCache.Contains(XmlCacheKey);
}
}
///// <summary>
///// 加载Html后是否清除所有注释节点。
///// </summary>
//private bool clearCommentOnLoad = false;
public XHtmlBase()
{
//License.Check(DAL.DalCreate.XHtmlClient);
_XmlDocument = new XmlDocument();
theCache = CacheManage.LocalInstance;
}
protected void LoadNameSpace(string nameSpace)
{
xnm = new XmlNamespaceManager(_XmlDocument.NameTable);
xnm.AddNamespace(PreXml, nameSpace);
}
/// <summary>
/// 从绝对路径中获得文件名做为Key值
/// </summary>
private string GenerateKey(string fileName)
{
_FileName = fileName;
fileName = fileName.Replace(AppConfig.WebRootPath, "XHtmlBase_");
fileName = fileName.Replace("/", "").Replace("\\", "");
return fileName;
}
#region 加载xml
/// <summary>
/// docTypeHtml是一样的。
/// </summary>
protected static string docTypeHtml = string.Empty;
/// <summary>
/// 从xml字符串加载
/// </summary>
/// <param name="xml">xml字符串</param>
public void LoadXml(string xml)
{
try
{
if (xnm != null)
{
if (xml.StartsWith("<!DOCTYPE html"))
{
if (string.IsNullOrEmpty(docTypeHtml))
{
docTypeHtml = "<!DOCTYPE html PUBLIC \" -//W3C//DTD XHTML 1.0 Transitional//EN\" \"" + AppConfig.XHtml.DtdUri + "\">";
}
xml = xml.Replace(xml.Substring(0, xml.IndexOf('>') + 1), docTypeHtml);
}
// xml = xml.Replace("http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd", AppConfig.XHtml.DtdUri);
}
xml = Filter(xml);
_XmlDocument.LoadXml(xml);
}
catch (XmlException err)
{
throw new XmlException(err.Message);
}
}
/// <summary>
/// 从文件中加载Xml
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public bool Load(string fileName)
{
return Load(fileName, XmlCacheLevel.Lower);
}
/// <summary>
/// 加载XML
/// </summary>
public bool Load(string fileName, XmlCacheLevel level)
{
return Load(fileName, level, false);
}
/// <summary>
/// 加载Xml文件
/// </summary>
/// <param name="fileName">文件名</param>
/// <param name="level">文件缓存级别</param>
/// <param name="clearCommentNode">加载后是否清除注释节点</param>
public bool Load(string fileName, XmlCacheLevel level, bool clearCommentNode)
{
bool loadState = false;
XmlCacheKey = GenerateKey(fileName);//从路径中获得文件名做为key
if (level != XmlCacheLevel.NoCache)
{
loadState = LoadFromCache(XmlCacheKey);//从Cache加载Xml
}
if (!loadState)//Cache加载Xml失败
{
_CacheMinutes = (double)level;
loadState = LoadFromFile(fileName, clearCommentNode);//从文件加载Xml
}
return loadState;
}
/// <summary>
/// 从缓存中加载html
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public bool LoadFromCache(string key)
{
if (theCache.Contains(key))//缓存中存在对应值是key的对象
{
if (_IsNoClone)
{
_XmlDocument = theCache.Get(key) as XmlDocument;
}
else
{
_XmlDocument = GetCloneFrom(theCache.Get(key) as XmlDocument);
}
_IsLoadFromCache = true;
return true;
}
else
{
return false;
}
}
/// <summary>
/// 移除所有注释节点
/// </summary>
public virtual void RemoveCommentNode()
{
}
/// <summary>
/// 从文件加载XML (最终调用的方法)
/// </summary>
private bool LoadFromFile(string fileName, bool clearCommentNode)
{
if (!System.IO.File.Exists(fileName))
{
//Log.WriteLog("filename no exist : " + fileName);
return false;
}
try
{
string html = string.Empty;
if (xnm != null)
{
html = IOHelper.ReadAllText(fileName, 0, _Encoding);
ResolverDtd.Resolver(ref _XmlDocument);//指定,才能生成DTD文件到本地目录。
}
if (html != string.Empty)
{
LoadXml(html);//从字符串加载html
}
else
{
_XmlDocument.Load(fileName);//从文件加载xml
}
if (clearCommentNode)
{
RemoveCommentNode();
}
XmlCacheKey = GenerateKey(fileName);
if (!theCache.Contains(XmlCacheKey))
{
SaveToCache(XmlCacheKey, !IsNoClone);
}
return true;
}
catch (Exception err)
{
Error.Throw(err.Message + " FileName : " + fileName);
}
return false;
}
#endregion
#region 其它方法
/// <summary>
/// 将文档缓存到全局Cache中
/// </summary>
/// <param name="key">缓存的Key名称</param>
/// <param name="isClone">是否克隆副本存档</param>
public void SaveToCache(string key, bool isClone)
{
if (_CacheMinutes > 0)
{
SaveToCache(key, isClone, _CacheMinutes);
}
}
/// <summary>
/// 将文档缓存到全局Cache中
/// </summary>
/// <param name="key">缓存的Key名称</param>
/// <param name="isClone">是否克隆副本存档</param>
/// <param name="cacheTimeMinutes">存档的分钟数</param>
public void SaveToCache(string key, bool isClone, double cacheTimeMinutes)
{
if (_XmlDocument != null)
{
if (!isClone)
{
theCache.Set(key, _XmlDocument, cacheTimeMinutes, _FileName);//添加Cache缓存
}
else
{
theCache.Set(key, GetCloneFrom(_XmlDocument), cacheTimeMinutes, _FileName);//添加Cache缓存Clone
}
}
}
/// <summary>
/// 文件保存
/// </summary>
public bool Save()
{
return Save(_FileName);
}
/// <param name="fileName">指定保存路径</param>
public bool Save(string fileName)
{
if (Path.GetFileName(fileName).IndexOfAny(AppConst.InvalidFileNameChars) > -1)//包含无效的路径字符。
{
Log.Write("XHtmlBase.Save : InvalidPath : " + fileName, LogType.Error);
return false;
}
string xHtml = string.Empty;
if (_XmlDocument != null && _XmlDocument.InnerXml.Length > 0)
{
xHtml = _XmlDocument.InnerXml.Replace(AppConfig.XHtml.DtdUri, "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd");
}
if (!string.IsNullOrEmpty(xHtml))
{
if (Directory.Exists(Path.GetDirectoryName(fileName)))
{
try
{
File.WriteAllText(fileName, xHtml, _Encoding);
return true;
}
catch
{
Thread.Sleep(20);
try
{
File.WriteAllText(fileName, xHtml, _Encoding);
return true;
}
catch (Exception err)
{
Log.Write(err, LogType.Error);
}
}
//}
}
else
{
Log.Write("No exist path folder:" + fileName, LogType.Error);
}
}
return false;
}
private XmlDocument GetCloneFrom(XmlDocument xDoc)
{
XmlDocument newDoc = new XmlDocument();
//if (xnm != null)// && !AppConfig.XHtml.UseFileLoadXml
//{
// ResolverDtd.Resolver(ref newDoc); //不需要指定了,因为第一次已经生成了DTD文件到本地,另外路径已被替换指向本地。
//}
try
{
newDoc.LoadXml(xDoc.InnerXml);
}
catch (Exception err)
{
Log.Write(err, LogType.Error);
newDoc.InnerXml = xDoc.InnerXml;
}
return newDoc;
}
protected XmlNode Fill(string xPath, XmlNode parent)
{
try
{
if (parent != null)
{
return parent.SelectSingleNode(xPath.Replace("//", "descendant::"), xnm);
}
return _XmlDocument.SelectSingleNode(xPath, xnm);
}
catch
{
return null;
}
}
protected XmlNodeList Select(string xPath, XmlNode parent)
{
try
{
if (parent != null)
{
return parent.SelectNodes(xPath.Replace("//", "descendant::"), xnm);
}
return _XmlDocument.SelectNodes(xPath, xnm);
}
catch
{
return null;
}
}
protected XmlElement Create(string tag)
{
if (xnm == null)
{
return _XmlDocument.CreateElement(tag);
}
return _XmlDocument.CreateElement(tag, xnm.LookupNamespace(PreXml));
}
protected string GetXPath(string tag, string attr, string value)
{
string xPath = "//" + (xnm != null ? PreXml + ":" : "") + tag; //+ "[@" + attr + "='" + value + "']";
if (!string.IsNullOrEmpty(attr))
{
if (!string.IsNullOrEmpty(value))
{
//忽略大小写搜索
//xPath += "[@" + attr + "='" + value + "']";
xPath += "[translate(@" + attr + ",'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')='" + value.ToLower() + "']";
//xPath += "[@" + attr + "=translate('" + value + "','ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')]";
}
else
{
xPath += "[@" + attr + "]";
}
}
return xPath;
}
/// <summary>
/// 给指定的字符加上CDATA
/// </summary>
/// <param name="text">对象字符</param>
/// <returns></returns>
public string SetCDATA(string text)
{
if (string.IsNullOrEmpty(text))
{
return text;
}
text = text.Replace(AppConfig.XHtml.CDataLeft, string.Empty).Replace(AppConfig.XHtml.CDataRight, string.Empty);
text = text.Replace("<![CDATA[", "<![CDATA[").Replace("]]>", "]]>");
//text = text.Replace(((char)10).ToString(), "<BR>");
//text = text.Replace(((char)13).ToString(), "<BR>");
//text = text.Replace(((char)34).ToString(), """);
//text = text.Replace(((char)39).ToString(), "'");
text = text.Replace("\\", "#!!#").Replace("\0", "#!0!#");
text = Filter(text);
return AppConfig.XHtml.CDataLeft + text + AppConfig.XHtml.CDataRight;
}
/// <summary>
/// 清除CDATA
/// </summary>
/// <param name="text">对象字符</param>
/// <returns></returns>
public string ClearCDATA(string text)
{
if (string.IsNullOrEmpty(text))
{
return text;
}
text = text.Replace("#!!#", "\\").Replace("#!0!#", "\\0");
text = text.Replace(AppConfig.XHtml.CDataLeft, string.Empty).Replace(AppConfig.XHtml.CDataRight, string.Empty);
return text;
}
/// <summary>
/// 过滤XML(十六进制值 0x1D)无效的字符(同时替换>符号)
/// </summary>
protected string Filter(string text)
{
if (string.IsNullOrEmpty(text))
{
return text;
}
StringBuilder info = new StringBuilder(text.Length + 20);
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
if (((c >= 0) && (c <= 8)) || ((c >= 11) && (c <= 12)) || ((c >= 14) && (c <= 32)))
{
info.AppendFormat(" ", c);//&#x{0:X};
}
else if (c == '&')
{
info.Append("&");
// &(逻辑与) &
//<(小于) <
//>(大于) >
//"(双引号) "
//'(单引号) '
}
else
{
if (i > 50 && i != text.Length - 1)
{
char nc = text[i + 1];
if (c == '<' && nc != '/' && nc != '!' && !IsEnChar(nc)) // 非英文字母。
{
info.Append("<");
continue;
}
}
info.Append(c);
}
}
return info.ToString();
}
private bool IsEnChar(char c)//英文字母
{
return (c > 64 && c < 91) || (c > 96 && c < 123);
}
///// <summary>
///// 二次正则替换。
///// </summary>
//private string RegexReplace(string text)
//{
// Regex regex = new Regex(@"</?[^>]*>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
// MatchCollection collection = regex.Matches(text);
// foreach (Match mat in collection)
// {
// string value = mat.Value;
// }
// return text;
//}
#endregion
#region IDisposable 成员
/// <summary>
/// 释放资源
/// </summary>
public virtual void Dispose()
{
if (_XmlDocument != null)
{
//if (!ReadOnly)
//{
//xmlDoc.RemoveAll();
//}
_XmlDocument = null;
//GC.Collect();
}
}
#endregion
}
}