forked from ying32/htmlparser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHtmlParserEx.pas
2515 lines (2263 loc) · 69.6 KB
/
HtmlParserEx.pas
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{
Html解析器.
最近因为用到Html解析功能.在网上找了几款Delphi版本的,结果发现解析复杂的HTML都有一些问题.
没办法自己写了一款,经测试到现在没遇到任何解析不了的Html.
wr960204 武稀松 2013
http://www.raysoftware.cn/?p=370
感谢牛人杨延哲在HTML语法和CSS语法方面的帮助.
Thank Yang Yanzhe.
http://www.pockhero.com/
本版本只支持DelphiXE3之后的版本.如果用早期Delphi请使用HTMLParser.pas文件.
支持Windows,MacOSX,iOS,Android平台,完全去掉了对指针的使用.防止以后易博龙去掉
移动平台对指针的支持.
脱离了对旧版本的支持,甩掉包袱开发起来真的很爽!
---------------------------------------------------------------------------------
ying32修改记录
Email:[email protected]
2017年06月20日
1、为IHtmlElementList增加for in 语法支持
2017年05月04日
1、去除RegularExpressions单元的引用,不再使用TRegEx改使用RegularExpressionsCore单元中的TPerlRegEx
2017年04月19日
1、增加使用XPath功能的编译指令"UseXPath",默认不使用XPath,个人感觉没什么用
2016年11月23日
1、简单支持XPath,简单的吧,利用xpath转css selector,嘿
xpath转换的代码改自python版本:https://github.com/santiycr/cssify/blob/master/cssify.py
另外对正则System.RegularExpressions.pas中TGroupCollection.GetItem进行了改进,没有找到命名组
且非PCRE_ERROR_NOSUBSTRING时返回空的,而不是抛出一个异常。暂时就简单粗爆的直接改吧,官方网站
上看到有人提过这个QC,不知道后面有没有解决。
2016年11月15日
IHtmlElement和THtmlElement的改变:
1、Attributes属性增加Set方法
2、TagName属性增加Set方法
3、增加Parent属性
4、增加RemoveAttr方法
5、增加Remove方法
6、增加RemoveChild方法
7、增加Find方法,此为SimpleCSSSelector的一个另名
8、_GetHtml不再直接附加FOrignal属性值,而是使用GetSelfHtml重新对修改后的元素进行赋值操作,并更新FOrignal的值
9、增加Text属性
使用例:
EL.Attributes['class'] := 'xxxx';
EL.TagName = 'a';
EL.Remove 移除自己
EL.RemoveChild(El2);
El.Find('a');
IHtmlElementList和THtmlElementList的改变:
1、增加RemoveAll方法
2、增加Remove方法
3、增加Each方法
4、增加Text属性
// 使用例:
// 移除选择的元素
LHtml.Find('a').RemoveAll
// 查找并遍沥
LHtml.Find('a').Each(
procedure(AIndex: Integer; AEl: IHtmlElement)
begin
Writeln('Index=', AIndex, ', href=', AEl.Attributes['href']);
end);
// 直接输出,仅选中的第一个元素
Writeln(LHtml.Find('title').Text);
}
unit HtmlParserEx;
{'$DEFINE UseXPath}
interface
uses
SysUtils,
Classes,
Generics.Collections
{$IFDEF UseXPath}
,RegularExpressionsCore
{$ENDIF};
{$IF (defined(IOS) and defined(CPUARM)) or defined(ANDROID)}
{$DEFINE MOBILE_DEV}
{$ENDIF}
const
LowStrIndex = Low(string); // 移动平台=0,个人电脑平台=1
type
{$IFNDEF MSWINDOWS}
{ 接口使用WideString是为了可以给例如C++,VB等语言使用.
但是如果离开了Windows平台,其他平台是没有WideString这个COM的数据类型的.
}
WideString = String;
{$ENDIF}
IHtmlElement = interface;
IHtmlElementList = interface;
TElementEachEvent = reference to procedure(AIndex: Integer; AEl: IHtmlElement);
IHtmlElement = interface
['{8C75239C-8CFA-499F-B115-7CEBEDFB421B}']
function GetParent: IHtmlElement; stdcall;
function GetTagName: WideString; safecall;
procedure SetTagName(Value: WideString); safecall;
function GetContent: WideString; safecall;
function GetOrignal: WideString; safecall;
function GetChildrenCount: Integer; stdcall;
function GetChildren(Index: Integer): IHtmlElement; stdcall;
function GetCloseTag: IHtmlElement; stdcall;
function GetInnerHtml(): WideString; safecall;
function GetOuterHtml(): WideString; safecall;
function GetInnerText(): WideString; safecall;
procedure SetInnerText(Value: WideString); safecall;
function GetAttributes(Key: WideString): WideString; safecall;
procedure SetAttributes(Key: WideString; Value: WideString); safecall;
procedure RemoveAttr(AAttrName: string); safecall;
function GetSourceLineNum(): Integer; stdcall;
function GetSourceColNum(): Integer; stdcall;
// 增加移除节点
function RemoveChild(ANode: IHtmlElement): Integer; stdcall;
procedure Remove; stdcall;
function AppedChild(const ATag: string): IHtmlElement; stdcall;
// 属性是否存在
function HasAttribute(AttributeName: WideString): Boolean; stdcall;
{ 用CSS选择器语法查找Element,不支持"伪类"
CSS Selector Style search,not support Pseudo-classes.
http://www.w3.org/TR/CSS2/selector.html
}
function SimpleCSSSelector(const selector: WideString): IHtmlElementList; stdcall;
function Find(const selector: WideString): IHtmlElementList; stdcall;
{$IFDEF UseXPath}
function FindX(const AXPath: WideString): IHtmlElementList; stdcall;
{$ENDIF}
// 枚举属性
function EnumAttributeNames(Index: Integer): WideString; safecall;
property TagName: WideString read GetTagName write SetTagName;
property ChildrenCount: Integer read GetChildrenCount;
property Children[index: Integer]: IHtmlElement read GetChildren; default;
property CloseTag: IHtmlElement read GetCloseTag;
property Content: WideString read GetContent;
property Orignal: WideString read GetOrignal;
property Parent: IHtmlElement read GetParent;
// 获取元素在源代码中的位置
property SourceLineNum: Integer read GetSourceLineNum;
property SourceColNum: Integer read GetSourceColNum;
//
property InnerHtml: WideString read GetInnerHtml;
property OuterHtml: WideString read GetOuterHtml;
property InnerText: WideString read GetInnerText write SetInnerText;
property Text: WideString read GetInnerText write SetInnerText;
property Attributes[Key: WideString]: WideString read GetAttributes write SetAttributes;
end;
THtmlListEnumerator = class
private
FIndex: Integer;
FList: IHtmlElementList;
public
constructor Create(AList: IHtmlElementList);
function GetCurrent: IHtmlElement; inline;
function MoveNext: Boolean;
property Current: IHtmlElement read GetCurrent;
end;
IHtmlElementList = interface
['{8E1380C6-4263-4BF6-8D10-091A86D8E7D9}']
function GetCount: Integer; stdcall;
function GetItems(Index: Integer): IHtmlElement; stdcall;
procedure RemoveAll; stdcall;
procedure Remove(ANode: IHtmlElement); stdcall;
procedure Each(f: TElementEachEvent); stdcall;
function GetText: WideString; stdcall;
function GetEnumerator: THtmlListEnumerator;
property Text: WideString read GetText;
property Count: Integer read GetCount;
property Items[Index: Integer]: IHtmlElement read GetItems; default;
end;
function ParserHTML(const Source: WideString): IHtmlElement; stdcall;
implementation
type
TStringDictionary = TDictionary<string, string>;
TPropDictionary = TDictionary<string, WORD>;
TStringDynArray = TArray<string>;
const
WhiteSpace = [' ', #13, #10, #9];
// CSS Attribute Compare Operator
OperatorChar = ['=', '!', '*', '~', '|', '^', '$'];
MaxListSize = Maxint div 16;
// TagProperty
tpBlock = $01;
tpInline = $02;
tpEmpty = $04;
tpFormatAsInline = $08;
tpPreserveWhitespace = $10;
tpInlineOrEmpty = tpInline or tpEmpty;
type
TAttrOperator = (aoExist, aoEqual, aoNotEqual, aoIncludeWord, aoBeginWord,
aoBegin, aoEnd, aoContain);
PAttrSelectorItem = ^TAttrSelectorItem;
TAttrSelectorItem = record
Key: string;
AttrOperator: TAttrOperator;
Value: string;
end;
TSelectorItemRelation = (sirNONE, sirDescendant, sirChildren,
sirYoungerBrother, sirAllYoungerBrother);
PCSSSelectorItem = ^TCSSSelectorItem;
TCSSSelectorItem = record
Relation: TSelectorItemRelation;
szTag: string;
Attributes: array of TAttrSelectorItem;
end;
TCSSSelectorItems = array of TCSSSelectorItem;
PCSSSelectorItems = ^TCSSSelectorItems;
TCSSSelectorItemGroup = array of TCSSSelectorItems;
//
TSourceContext = record
private
function GetCharOfCurrent(Index: Integer): Char; inline;
public
Code: String;
CodeIndex: Integer;
LineNum: Integer;
ColNum: Integer;
CurrentChar: Char;
{$IFDEF DEBUG}
currentCode: PChar;
{$ENDIF}
procedure IncSrc(); overload; inline;
procedure IncSrc(Step: Integer); overload; inline;
procedure setCode(const ACode: string); inline;
function ReadStr(UntilChars: TSysCharSet): string; inline;
function PeekStr(Index: Integer): string; overload; inline;
function PeekStr(): string; overload; inline;
function subStr(Index, Count: Integer): string; overload; inline;
function subStr(Count: Integer): string; overload; inline;
procedure SkipBlank(); inline;
property charOfCurrent[Index: Integer]: Char read GetCharOfCurrent;
end;
TAttributeItem = record
Key, Value: string;
end;
TAttributeDynArray = TArray<TAttributeItem>;
TIHtmlElementList = class;
THtmlElement = class;
THtmlElementList = TList<THtmlElement>;
THtmlElement = class(TInterfacedObject, IHtmlElement)
private
function GetChildrens: IHtmlElementList;
protected
// ying32
function GetParent: IHtmlElement; stdcall;
function GetTagName: WideString; safecall;
procedure SetTagName(Value: WideString); safecall;
function GetContent: WideString; safecall;
function GetOrignal: WideString; safecall;
function GetChildrenCount: Integer; stdcall;
function GetChildren(Index: Integer): IHtmlElement; stdcall;
function GetCloseTag: IHtmlElement; stdcall;
function GetInnerHtml(): WideString; safecall;
function GetOuterHtml(): WideString; safecall;
function GetInnerText(): WideString; safecall;
procedure SetInnerText(Value: WideString); safecall;
function GetAttributes(Key: WideString): WideString; safecall;
procedure SetAttributes(Key: WideString; Value: WideString); safecall;
procedure RemoveAttr(AAttrName: string); safecall;
function GetSourceLineNum(): Integer; stdcall;
function GetSourceColNum(): Integer; stdcall;
// ying32添加
function RemoveChild(ANode: IHtmlElement): Integer; stdcall;
procedure Remove; stdcall;
function AppedChild(const ATag: string): IHtmlElement; stdcall;
// 属性是否存在
function HasAttribute(AttributeName: WideString): Boolean; stdcall;
{ 用CSS选择器语法查找Element,不支持"伪类"
CSS Selector Style search,not support Pseudo-classes.
http://www.w3.org/TR/CSS2/selector.html
}
function SimpleCSSSelector(const selector: WideString): IHtmlElementList; stdcall;
function Find(const selector: WideString): IHtmlElementList; stdcall;
{$IFDEF UseXPath}
function FindX(const AXPath: WideString): IHtmlElementList; stdcall;
{$ENDIF}
// 枚举属性
function EnumAttributeNames(Index: Integer): WideString; safecall;
property TagName: WideString read GetTagName write SetTagName;
property ChildrenCount: Integer read GetChildrenCount;
property Children[index: Integer]: IHtmlElement read GetChildren; default;
property CloseTag: IHtmlElement read GetCloseTag;
property Content: WideString read GetContent;
property Orignal: WideString read GetOrignal;
property Parent: IHtmlElement read GetParent;
// 获取元素在源代码中的位置
property SourceLineNum: Integer read GetSourceLineNum;
property SourceColNum: Integer read GetSourceColNum;
//
property InnerHtml: WideString read GetInnerHtml;
property OuterHtml: WideString read GetOuterHtml;
property InnerText: WideString read GetInnerText;
property Attributes[Key: WideString]: WideString read GetAttributes write SetAttributes;
property Childrens: IHtmlElementList read GetChildrens;
private
FClosed: Boolean;
//
FOwner: THtmlElement;
FCloseTag: IHtmlElement;
FTagName: string;
FIsCloseTag: Boolean;
FContent: string;
FOrignal: string;
FSourceLine: Integer;
FSourceCol: Integer;
//
FAttributes: TStringDictionary;
FChildren: TIHtmlElementList;
procedure _GetHtml(IncludeSelf: Boolean; Sb: TStringBuilder);
procedure _GetText(IncludeSelf: Boolean; Sb: TStringBuilder);
procedure _SimpleCSSSelector(const ItemGroup: TCSSSelectorItemGroup; r: TIHtmlElementList);
procedure _Select(Item: PCSSSelectorItem; Count: Integer; r: TIHtmlElementList; OnlyTopLevel: Boolean = false);
public
constructor Create(AOwner: THtmlElement; AText: string; ALine, ACol: Integer);
destructor Destroy; override;
end;
TIHtmlElementList = class(TInterfacedObject, IHtmlElementList)
private
// IHtmlElementList
function GetItems(Index: Integer): IHtmlElement; stdcall;
function GetCount: Integer; stdcall;
protected
FList: TList<IHtmlElement>;
procedure SetItems(Index: Integer; const Value: IHtmlElement); inline;
function Add(Value: IHtmlElement): Integer; inline;
procedure Delete(Index: Integer); inline;
procedure Clear; inline;
// ying32添加
procedure RemoveAll; stdcall;
procedure Remove(ANode: IHtmlElement); stdcall;
procedure Each(f: TElementEachEvent); stdcall;
function GetText: WideString; stdcall;
public
constructor Create;
destructor Destroy; override;
function GetEnumerator: THtmlListEnumerator;
function IndexOf(Item: IHtmlElement): Integer;
// IHtmlElementList
property Items[index: Integer]: IHtmlElement read GetItems write SetItems; default;
property Count: Integer read GetCount;
end;
function SplitStr(ACharSet: TSysCharSet; AStr: string): TStringDynArray;
var
L, I: Integer;
S: string;
StrChar: Char;
begin
Result := nil;
if Length(AStr) <= 0 then
Exit;
I := Low(AStr);
L := Low(AStr);
StrChar := #0;
while I <= High(AStr) do
begin
if CharInSet(AStr[I], ['''', '"']) then
if StrChar = #0 then
StrChar := AStr[I]
else if StrChar = AStr[I] then
StrChar := #0;
// 不在字符串中,分隔符才生效
if StrChar = #0 then
if CharInSet(AStr[I], ACharSet) then
begin
if I > L then
begin
S := Copy(AStr, L{$IF (LowStrIndex = 0)} + 1{$ENDIF}, I - L);
SetLength(Result, Length(Result) + 1);
Result[Length(Result) - 1] := S;
end;
L := I + 1;
end;
Inc(I);
end;
if (I > L) then
begin
S := Copy(AStr, L{$IF (LowStrIndex = 0)} + 1{$ENDIF}, I - L);
SetLength(Result, Length(Result) + 1);
Result[Length(Result) - 1] := S;
end;
end;
function StrRight(const Value: string; Count: Integer): string;
var
start: Integer;
begin
start := Length(Value) - Count + 1;
if start <= 0 then
Result := Value
else
Result := Copy(Value, start, Count);
end;
function StrLeft(const Value: string; Count: Integer): string;
begin
Result := Copy(Value, LowStrIndex, Count);
end;
// ComapreAttr
function _aoExist(const Item: TAttrSelectorItem; E: THtmlElement): Boolean;
begin
Result := E.FAttributes.ContainsKey(Item.Key);
end;
function _aoEqual(const Item: TAttrSelectorItem; E: THtmlElement): Boolean;
begin
Result := E.FAttributes.ContainsKey(Item.Key) and
(E.FAttributes[Item.Key] = Item.Value);
end;
function _aoNotEqual(const Item: TAttrSelectorItem; E: THtmlElement): Boolean;
begin
Result := E.FAttributes.ContainsKey(Item.Key) and
(E.FAttributes[Item.Key] <> Item.Value);
end;
function _aoIncludeWord(const Item: TAttrSelectorItem; E: THtmlElement)
: Boolean;
var
S: TStringDynArray;
I: Integer;
begin
Result := false;
if not E.FAttributes.ContainsKey(Item.Key) then
Exit;
Result := True;
S := SplitStr(WhiteSpace, E.FAttributes[Item.Key]);
for I := Low(S) to High(S) do
if S[I] = Item.Value then
Exit;
Result := false;
end;
function _aoBeginWord(const Item: TAttrSelectorItem; E: THtmlElement): Boolean;
var
S: TStringDynArray;
I: Integer;
begin
Result := false;
if not E.FAttributes.ContainsKey(Item.Key) then
Exit;
S := SplitStr((WhiteSpace + ['_', '-']), E.FAttributes[Item.Key]);
Result := (Length(S) > 0) and (S[0] = Item.Value);
end;
function _aoBegin(const Item: TAttrSelectorItem; E: THtmlElement): Boolean;
var
attr, Value: string;
begin
Result := false;
if not E.FAttributes.ContainsKey(Item.Key) then
Exit;
attr := E.FAttributes[Item.Key];
Value := Item.Value;
Result := (Length(attr) > Length(Value)) and
(StrLeft(attr, Length(Value)) = Value);
end;
function _aoEnd(const Item: TAttrSelectorItem; E: THtmlElement): Boolean;
var
attr, Value: string;
begin
Result := false;
if not E.FAttributes.ContainsKey(Item.Key) then
Exit;
attr := E.FAttributes[Item.Key];
Value := Item.Value;
Result := (Length(attr) > Length(Value)) and
(StrRight(attr, Length(Value)) = Value);
end;
function _aoContain(const Item: TAttrSelectorItem; E: THtmlElement): Boolean;
begin
Result := false;
if not E.FAttributes.ContainsKey(Item.Key) then
Exit;
Result := Pos(Item.Value, E.FAttributes[Item.Key]) > 0;
end;
type
TFNCompareAttr = function(const Item: TAttrSelectorItem;
E: THtmlElement): Boolean;
const
AttrCompareFuns: array [TAttrOperator] of TFNCompareAttr = (_aoExist,
_aoEqual, _aoNotEqual, _aoIncludeWord, _aoBeginWord, _aoBegin, _aoEnd,
_aoContain);
function ConvertEntities(S: String): string; forward;
function GetTagProperty(const TagName: string): WORD; forward;
procedure DoError(const Msg: string);
begin
raise Exception.Create(Msg);
end;
procedure _ParserAttrs(var sc: TSourceContext; var Attrs: TAttributeDynArray);
var
Item: TAttributeItem;
begin
SetLength(Attrs, 0);
while True do
begin
sc.SkipBlank();
if sc.CurrentChar = #0 then
Break;
Item.Key := sc.ReadStr((WhiteSpace + [#0, '=']));
Item.Value := '';
sc.SkipBlank;
if sc.CurrentChar = '=' then
begin
sc.IncSrc;
sc.SkipBlank;
Item.Value := sc.ReadStr((WhiteSpace + [#0]));
end;
SetLength(Attrs, Length(Attrs) + 1);
Attrs[Length(Attrs) - 1] := Item;
end;
end;
procedure _ParserNodeItem(S: string; var ATagName: string;
var Attrs: TAttributeDynArray);
var
sc: TSourceContext;
begin
sc.setCode(S);
sc.SkipBlank;
ATagName := UpperCase(sc.ReadStr((WhiteSpace + [#0, '/', '>'])));
_ParserAttrs(sc, Attrs);
end;
function CreateTextElement(AOwner: THtmlElement; AText: string;
ALine, ACol: Integer): THtmlElement;
begin
Result := THtmlElement.Create(AOwner, AText, ALine, ACol);
with Result do
begin
FContent := ConvertEntities(AText);
FTagName := '#TEXT';
FClosed := True;
end;
end;
function CreateScriptElement(AOwner: THtmlElement; AText: string;
ALine, ACol: Integer): THtmlElement;
begin
Result := THtmlElement.Create(AOwner, AText, ALine, ACol);
with Result do
begin
FContent := ConvertEntities(AText);
FTagName := '#SCRIPT';
FClosed := True;
end;
end;
function CreateStyleElement(AOwner: THtmlElement; AText: string;
ALine, ACol: Integer): THtmlElement;
begin
Result := THtmlElement.Create(AOwner, AText, ALine, ACol);
with Result do
begin
FContent := ConvertEntities(AText);
FTagName := '#STYLE';
FClosed := True;
end;
end;
function CreateCommentElement(AOwner: THtmlElement; AText: string;
ALine, ACol: Integer): THtmlElement;
begin
Result := THtmlElement.Create(AOwner, AText, ALine, ACol);
with Result do
begin
FContent := ConvertEntities(AText);
FTagName := '#COMMENT';
FClosed := True;
end;
end;
function CreateTagElement(AOwner: THtmlElement; AText: string;
ALine, ACol: Integer): THtmlElement;
var
Strs: TStringDynArray;
I: Integer;
Attrs: TAttributeDynArray;
begin
Result := THtmlElement.Create(AOwner, AText, ALine, ACol);
with Result do
begin
// TODO 解析TagName和属性
if AText = '' then
Exit;
// 去掉两头的<
if AText[Low(AText)] = '<' then
AText := StrRight(AText, Length(AText) - 1);
if AText = '' then
Exit;
if AText[High(AText)] = '>' then
AText := StrLeft(AText, Length(AText) - 1);
// 检查是关闭节点,还是单个已经关闭的节点
if AText = '' then
Exit;
FClosed := AText[High(AText)] = '/';
FIsCloseTag := AText[LowStrIndex] = '/';
if FIsCloseTag then
AText := StrRight(AText, Length(AText) - 1);
if FClosed then
AText := StrLeft(AText, Length(AText) - 1);
//
_ParserNodeItem(AText, FTagName, Attrs);
for I := Low(Attrs) to High(Attrs) do
FAttributes.AddOrSetValue(LowerCase(Attrs[I].Key),
ConvertEntities(Attrs[I].Value));
end;
end;
function CreateDocTypeElement(AOwner: THtmlElement; AText: string;
ALine, ACol: Integer): THtmlElement;
begin
Result := THtmlElement.Create(AOwner, AText, ALine, ACol);
with Result do
begin
FContent := ConvertEntities(AText);
FTagName := '#DOCTYPE';
FClosed := True;
if FContent = '' then
Exit;
if FContent[1] = '<' then
Delete(FContent, 1, 1);
if FContent = '' then
Exit;
if FContent[Length(FContent)] = '>' then
Delete(FContent, Length(FContent), 1);
FContent := Trim(Copy(Trim(FContent), 9, Length(FContent)));
end;
end;
procedure _ParserHTML(const Source: string; AElementList: THtmlElementList);
var
BeginLineNum, BeginColNum: Integer;
sc: TSourceContext;
function IsEndOfTag(TagName: string): Boolean;
begin
Result := false;
if sc.charOfCurrent[1] = '/' then
begin
Result := UpperCase(sc.subStr(sc.CodeIndex + 2, Length(TagName)))
= UpperCase(TagName);
end;
end;
function PosCharInTag(AChar: Char): Boolean;
var
StrChar: Char;
begin
Result := false;
StrChar := #0;
while True do
begin
if sc.CurrentChar = #0 then
Break;
if sc.CurrentChar = '"' then
begin
if StrChar = #0 then
StrChar := sc.CurrentChar
else
StrChar := #0;
end;
if (sc.CurrentChar = AChar) and (StrChar = #0) then
begin
Result := True;
Break;
end;
sc.IncSrc;
end;
end;
function ParserStyleData(): string;
var
oldIndex: Integer;
begin
oldIndex := sc.CodeIndex;
if sc.subStr(4) = '<!--' then
begin
sc.IncSrc(5);
while True do
begin
if sc.CurrentChar = #0 then
DoError(Format('未完结的Style行:%d;列:%d;', [sc.LineNum, sc.ColNum]))
else if sc.CurrentChar = '>' then
begin
if (sc.charOfCurrent[-1] = '-') and (sc.charOfCurrent[-2] = '-') then
begin
sc.IncSrc;
sc.SkipBlank();
Break;
end;
end;
sc.IncSrc;
end;
end
else
while True do
begin
case sc.CurrentChar of
#0:
begin
Break;
end;
'<':
begin
if IsEndOfTag('style') then
begin
Break;
end;
end;
end;
sc.IncSrc;
end;
Result := sc.subStr(oldIndex, sc.CodeIndex - oldIndex);
end;
function ParserScriptData(): string;
var
oldIndex: Integer;
stringChar: Char;
PreIsblique: Boolean;
begin
oldIndex := sc.CodeIndex;
stringChar := #0;
sc.SkipBlank();
if sc.subStr(4) = '<!--' then
begin
sc.IncSrc(5);
while True do
begin
if sc.CurrentChar = #0 then
DoError(Format('未完结的Script行:%d;列:%d;', [sc.LineNum, sc.ColNum]))
else if sc.CurrentChar = '>' then
begin
if (sc.charOfCurrent[-1] = '-') and (sc.charOfCurrent[-2] = '-') then
begin
sc.IncSrc;
sc.SkipBlank();
Break;
end;
end;
sc.IncSrc;
end;
end
else
begin
while True do
begin
case sc.CurrentChar of
#0:
Break;
'"', '''': // 字符串
begin
stringChar := sc.CurrentChar;
PreIsblique := false;
sc.IncSrc();
while True do
begin
if sc.CurrentChar = #0 then
Break;
if (sc.CurrentChar = stringChar) and (not PreIsblique) then
Break;
if sc.CurrentChar = '\' then
PreIsblique := not PreIsblique
else
PreIsblique := false;
sc.IncSrc;
end;
end;
'/': // 注释
begin
sc.IncSrc();
case sc.CurrentChar of
'/': // 行注释
begin
while True do
begin
if CharInSet(sc.CurrentChar, [#0, #$0A]) then
begin
Break;
end;
sc.IncSrc();
end;
end;
'*': // 块注释
begin
sc.IncSrc();
sc.IncSrc();
while True do
begin
if sc.CurrentChar = #0 then
Break;
if (sc.CurrentChar = '/') and (sc.charOfCurrent[-1] = '*')
then
begin
Break;
end;
sc.IncSrc();
end;
end;
end;
end;
'<':
begin
if IsEndOfTag('script') then
begin
Break;
end;
end;
end;
sc.IncSrc();
end;
end;
Result := sc.subStr(oldIndex, sc.CodeIndex - oldIndex)
end;
var
ElementType: (EtUnknow, EtTag, EtDocType, EtText, EtComment);
OldCodeIndex: Integer;
tmp: string;
Tag: THtmlElement;
begin
sc.setCode(Source);
while sc.CodeIndex <= high(sc.Code) do
begin
ElementType := EtUnknow;
OldCodeIndex := sc.CodeIndex;
BeginLineNum := sc.LineNum;
BeginColNum := sc.ColNum;
if sc.CurrentChar = #0 then
Break;
// "<"开头的就是Tag之类的
if sc.CurrentChar = '<' then
begin
sc.IncSrc;
if sc.CurrentChar = '!' then // 注释
begin
ElementType := EtComment;
sc.IncSrc;
case sc.CurrentChar of
'-': // <!-- -->
begin
sc.IncSrc; // -
while True do
begin
if not PosCharInTag('>') then
DoError('LineNum:' + IntToStr(BeginLineNum) + '无法找到Tag结束点:' +
sc.subStr(100))
else if (sc.charOfCurrent[-1] = '-') and
(sc.charOfCurrent[-2] = '-') then
begin
sc.IncSrc;
Break;
end;
sc.IncSrc;
end;
end;
'[': // <![CDATA[.....]]>
begin
sc.IncSrc; //
while True do
begin
if not PosCharInTag('>') then
DoError('LineNum:' + IntToStr(BeginLineNum) + '无法找到Tag结束点:' +
sc.subStr(100))
else if (sc.charOfCurrent[-1] = ']') then
begin
sc.IncSrc;
Break;
end;
sc.IncSrc;
end;
end;
else // <!.....>
begin
if UpperCase(sc.PeekStr()) = 'DOCTYPE' then
begin
ElementType := EtDocType;
sc.IncSrc; //
if PosCharInTag('>') then
sc.IncSrc
else
DoError('LineNum:' + IntToStr(BeginLineNum) + '无法找到Tag结束点:' +
sc.subStr(100));
end
else
begin
sc.IncSrc; //
if PosCharInTag('>') then
sc.IncSrc
else
DoError('LineNum:' + IntToStr(BeginLineNum) + '无法找到Tag结束点:' +
sc.subStr(100));
end;
end;
end;
end
else if sc.CurrentChar = '?' then // <?...?> XML
begin
ElementType := EtComment;
sc.IncSrc; //