forked from radprogrammer/HTMLParserEx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HtmlParserEx.pas
2394 lines (2253 loc) · 72.1 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
unit HtmlParserEx;
{$DEFINE UseXPath }
{$IF RTLVersion < 24.0}
{$MESSAGE ERROR 'Only XE3 and later versions are supported'}
{$ENDIF}
interface
uses
System.SysUtils,
System.Classes,
System.Generics.Collections
{$IFDEF UseXPath}
, System.RegularExpressionsCore
{$ENDIF};
{$IF (defined(IOS) and defined(CPUARM)) or defined(ANDROID)}
{$DEFINE MOBILE_DEV}
{$ENDIF}
const
// By design each IHtmlElement has a TagName property, even it's a 'Text' element.
// so cSpecialTagName_Text represents the fake tag name of a Text element
cSpecialTagName_Text = '#TEXT';
LowStrIndex = low(string); // Mobile platform=0, PC platform=1
type
IHtmlElement = interface;
IHtmlElementList = interface;
TElementEachEvent = reference to procedure(AIndex: Integer;
AEl: IHtmlElement);
TStringDictionary = TDictionary<string, string>;
IHtmlElement = interface
['{8C75239C-8CFA-499F-B115-7CEBEDFB421B}']
function GetParent: IHtmlElement; stdcall;
function GetTagName: String; stdcall;
procedure SetTagName(Value: String); stdcall;
function GetContent: String; stdcall;
function GetOrignal: String; stdcall;
function GetChildrenCount: Integer; stdcall;
function GetChildren(Index: Integer): IHtmlElement; overload; stdcall;
function GetChildren: IHtmlElementList; overload; stdcall;
function GetCloseTag: IHtmlElement; stdcall;
function GetInnerHtml(): String; stdcall;
function GetOuterHtml(): String; stdcall;
function GetInnerText(): String; stdcall;
procedure SetInnerText(Value: String); stdcall;
function GetAttributes(Key: String): String; overload; stdcall;
function GetAttributes: TStringDictionary; overload; stdcall;
procedure SetAttributes(Key: String; Value: String); stdcall;
procedure RemoveAttr(AAttrName: string); stdcall;
function GetSourceLineNum(): Integer; stdcall;
function GetSourceColNum(): Integer; stdcall;
// Add and remove nodes
function RemoveChild(ANode: IHtmlElement): Integer; stdcall;
procedure Remove; stdcall;
function AppedChild(const ATag: string): IHtmlElement; stdcall;
// Does the property exist
function HasAttribute(AttributeName: String): Boolean; stdcall;
{ Find Element using CSS selector syntax, "pseudo-class" is not supported
http://www.w3.org/TR/CSS2/selector.html
}
function SimpleCSSSelector(const selector: String)
: IHtmlElementList; stdcall;
function Find(const selector: String): IHtmlElementList; stdcall;
{$IFDEF UseXPath}
function FindX(const AXPath: String): IHtmlElementList; stdcall;
{$ENDIF}
// enum property
function EnumAttributeNames(Index: Integer): String; stdcall;
property TagName: String read GetTagName write SetTagName;
property ChildrenCount: Integer read GetChildrenCount;
property Children[index: Integer]: IHtmlElement read GetChildren; default;
property CloseTag: IHtmlElement read GetCloseTag;
property Content: String read GetContent;
property Orignal: String read GetOrignal;
property Parent: IHtmlElement read GetParent;
// Get the position of an element in the source code
property SourceLineNum: Integer read GetSourceLineNum;
property SourceColNum: Integer read GetSourceColNum;
//
property InnerHtml: String read GetInnerHtml;
property OuterHtml: String read GetOuterHtml;
property InnerText: String read GetInnerText write SetInnerText;
property Text: String read GetInnerText write SetInnerText;
property Attributes[Key: String]: String read GetAttributes
write SetAttributes;
property Attributes: TStringDictionary read GetAttributes;
property Children: IHTMLElementList read GetChildren;
// ying32 does not change the original, just simplifies the use
property Attrs[Key: String]: String 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: String; stdcall;
function GetEnumerator: THtmlListEnumerator;
property Text: String read GetText;
property Count: Integer read GetCount;
property Items[index: Integer]: IHtmlElement read GetItems; default;
end;
function ParserHTML(const Source: String): IHtmlElement; stdcall;
function DecodeHtmlEntities(S: string): string; forward;
implementation
uses
StrUtils;
type
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;
function PassedEndOfSourceCode: Boolean; inline;
public
SourceCode: string;
CharIndex: Integer;
LineNum: Integer;
ColNum: Integer;
CurrentChar: Char;
{$IFDEF DEBUG}
currentCode: PChar;
{$ENDIF}
// Jump to the next char and return true if not exceeding the end of SourceCode
function JumpToNextChar: Boolean; overload; inline;
// Jump multiple characters, and return the jumped steps
function JumpToNextChar(Step: Integer): 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)
protected
// ying32
function GetParent: IHtmlElement; stdcall;
function GetTagName: String; stdcall;
procedure SetTagName(Value: String); stdcall;
function GetContent: String; stdcall;
function GetOrignal: String; stdcall;
function GetChildrenCount: Integer; stdcall;
function GetChildren(Index: Integer): IHtmlElement; overload; stdcall;
function GetChildren: IHtmlElementList; overload; stdcall;
function GetCloseTag: IHtmlElement; stdcall;
function GetInnerHtml(): String; stdcall;
function GetOuterHtml(): String; stdcall;
function GetInnerText(): String; stdcall;
procedure SetInnerText(Value: String); stdcall;
function GetAttributes(Key: String): String; overload; stdcall;
function GetAttributes: TStringDictionary; overload; stdcall;
procedure SetAttributes(Key: String; Value: String); stdcall;
procedure RemoveAttr(AAttrName: string); stdcall;
function GetSourceLineNum(): Integer; stdcall;
function GetSourceColNum(): Integer; stdcall;
// ying32Added
function RemoveChild(ANode: IHtmlElement): Integer; stdcall;
procedure Remove; stdcall;
function AppedChild(const ATag: string): IHtmlElement; stdcall;
// Does the property exist
function HasAttribute(AttributeName: String): Boolean; stdcall;
{ Find Element with CSS selector syntax, does not support "pseudo-class"
http://www.w3.org/TR/CSS2/selector.html
}
function SimpleCSSSelector(const selector: String)
: IHtmlElementList; stdcall;
function Find(const selector: String): IHtmlElementList; stdcall;
{$IFDEF UseXPath}
function FindX(const AXPath: String): IHtmlElementList; stdcall;
{$ENDIF}
// enum property
function EnumAttributeNames(Index: Integer): String; stdcall;
property TagName: String read GetTagName write SetTagName;
property ChildrenCount: Integer read GetChildrenCount;
property Children[index: Integer]: IHtmlElement read GetChildren; default;
property CloseTag: IHtmlElement read GetCloseTag;
property Content: String read GetContent;
property Orignal: String read GetOrignal;
property Parent: IHtmlElement read GetParent;
// Get the position of an element in the source code
property SourceLineNum: Integer read GetSourceLineNum;
property SourceColNum: Integer read GetSourceColNum;
//
property InnerHtml: String read GetInnerHtml;
property OuterHtml: String read GetOuterHtml;
property InnerText: String read GetInnerText;
property Attributes[Key: String]: String read GetAttributes
write SetAttributes;
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;
// ying32Added
procedure RemoveAll; stdcall;
procedure Remove(ANode: IHtmlElement); stdcall;
procedure Each(f: TElementEachEvent); stdcall;
function GetText: String; 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;
// Not in the string, the delimiter takes effect
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;
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 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.JumpToNextChar;
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
// Edwin: 2019-07-08: html entities in the text element shouldn't be decoded?
// FContent := DecodeHtmlEntities(AText);
FContent := AText;
FTagName := cSpecialTagName_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
// Edwin: 2019-07-09: html entities in scripts shouldn't be decoded?
// FContent := DecodeHtmlEntities(AText);
FContent := 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
// Edwin: 2019-07-09: html entities in <style> tags shouldn't be decoded?
// FContent := DecodeHtmlEntities(AText);
FContent := 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
// Edwin: 2019-07-09: html entities in comments shouldn't be decoded?
// FContent := DecodeHtmlEntities(AText);
FContent := AText;
FTagName := '#COMMENT';
FClosed := True;
end;
end;
function CreateTagElement(AOwner: THtmlElement; AText: string;
ALine, ACol: Integer): THtmlElement;
var
I: Integer;
Attrs: TAttributeDynArray;
begin
Result := THtmlElement.Create(AOwner, AText, ALine, ACol);
with Result do
begin
// TODO parsing TagName and attributes
if AText = '' then
Exit;
// remove the <
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);
// Check if a node is down, or a single down node
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),
DecodeHtmlEntities(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 := DecodeHtmlEntities(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.CharIndex + 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.JumpToNextChar;
end;
end;
function ParserStyleData(): string;
var
oldIndex: Integer;
begin
oldIndex := sc.CharIndex;
if sc.subStr(4) = '<!--' then
begin
sc.JumpToNextChar(5);
while True do
begin
if sc.CurrentChar = #0 then
DoError(Format('Unfinished Style row: %d; Column: %d;',
[sc.LineNum, sc.ColNum]))
else if sc.CurrentChar = '>' then
begin
if (sc.charOfCurrent[-1] = '-') and (sc.charOfCurrent[-2] = '-') then
begin
sc.JumpToNextChar;
sc.SkipBlank();
Break;
end;
end;
sc.JumpToNextChar;
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.JumpToNextChar;
end;
Result := sc.subStr(oldIndex, sc.CharIndex - oldIndex);
end;
function ParserScriptData(): string;
var
oldIndex: Integer;
stringChar: Char;
PreIsblique: Boolean;
begin
oldIndex := sc.CharIndex;
sc.SkipBlank();
if sc.subStr(4) = '<!--' then
begin
sc.JumpToNextChar(5);
while True do
begin
if sc.CurrentChar = #0 then
DoError(Format('Unfinished script line: %d; column: %d;',
[sc.LineNum, sc.ColNum]))
else if sc.CurrentChar = '>' then
begin
if (sc.charOfCurrent[-1] = '-') and (sc.charOfCurrent[-2] = '-') then
begin
sc.JumpToNextChar;
sc.SkipBlank();
Break;
end;
end;
sc.JumpToNextChar;
end;
end
else
begin
while True do
begin
case sc.CurrentChar of
#0:
Break;
'"', '''': // string
begin
stringChar := sc.CurrentChar;
PreIsblique := false;
sc.JumpToNextChar();
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.JumpToNextChar;
end;
end;
'/': // Comments
begin
sc.JumpToNextChar();
case sc.CurrentChar of
'/': // line comment
begin
while True do
begin
if CharInSet(sc.CurrentChar, [#0, #$0A]) then
begin
Break;
end;
sc.JumpToNextChar();
end;
end;
'*': // block comment
begin
sc.JumpToNextChar();
sc.JumpToNextChar();
while True do
begin
if sc.CurrentChar = #0 then
Break;
if (sc.CurrentChar = '/') and (sc.charOfCurrent[-1] = '*')
then
begin
Break;
end;
sc.JumpToNextChar();
end;
end;
end;
end;
'<':
begin
if IsEndOfTag('script') then
begin
Break;
end;
end;
end;
sc.JumpToNextChar();
end;
end;
Result := sc.subStr(oldIndex, sc.CharIndex - oldIndex)
end;
var
ElementType: (EtUnknow, EtTag, EtDocType, EtText, EtComment);
OldCodeIndex: Integer;
tmp: string;
Tag: THtmlElement;
begin
sc.setCode(Source);
while sc.CharIndex <= high(sc.SourceCode) do
begin
OldCodeIndex := sc.CharIndex;
BeginLineNum := sc.LineNum;
BeginColNum := sc.ColNum;
if sc.CurrentChar = #0 then
Break;
// "<" It starts with something like Tag
if sc.CurrentChar = '<' then
begin
sc.JumpToNextChar;
if sc.CurrentChar = '!' then // Comments
begin
ElementType := EtComment;
sc.JumpToNextChar;
case sc.CurrentChar of
'-': // <!-- -->
begin
sc.JumpToNextChar; // -
while True do
begin
if not PosCharInTag('>') then
DoError('LineNum:' + IntToStr(BeginLineNum) +
'Unable to find tag end point:' + sc.subStr(100))
else if (sc.charOfCurrent[-1] = '-') and
(sc.charOfCurrent[-2] = '-') then
begin
sc.JumpToNextChar;
Break;
end;
sc.JumpToNextChar;
end;
end;
'[': // <![CDATA[.....]]>
begin
sc.JumpToNextChar; //
while True do
begin
if not PosCharInTag('>') then
DoError('LineNum:' + IntToStr(BeginLineNum) +
'Unable to find tag end point:' + sc.subStr(100))
else if (sc.charOfCurrent[-1] = ']') then
begin
sc.JumpToNextChar;
Break;
end;
sc.JumpToNextChar;
end;
end;
else // <!.....>
begin
if UpperCase(sc.PeekStr()) = 'DOCTYPE' then
begin
ElementType := EtDocType;
sc.JumpToNextChar; //
if PosCharInTag('>') then
sc.JumpToNextChar
else
DoError('LineNum:' + IntToStr(BeginLineNum) +
'Unable to find tag end point:' + sc.subStr(100));
end
else
begin
sc.JumpToNextChar; //
if PosCharInTag('>') then
sc.JumpToNextChar
else
DoError('LineNum:' + IntToStr(BeginLineNum) +
'Unable to find tag end point:' + sc.subStr(100));
end;
end;
end;
end
else if sc.CurrentChar = '?' then // <?...?> XML
begin
ElementType := EtComment;
sc.JumpToNextChar; //
while True do
begin
if not PosCharInTag('>') then
DoError('LineNum:' + IntToStr(BeginLineNum) +
'Unable to find tag end point:' + sc.subStr(100))
else if (sc.charOfCurrent[-1] = '?') then
begin
sc.JumpToNextChar;
Break;
end;
sc.JumpToNextChar;
end;
end
else // normal node
begin
ElementType := EtTag;
sc.JumpToNextChar;
if PosCharInTag('>') then
sc.JumpToNextChar
else
DoError('LineNum:' + IntToStr(BeginLineNum) +
'Unable to find tag end point:' + sc.subStr(100));
end;
tmp := sc.subStr(OldCodeIndex, sc.CharIndex - OldCodeIndex);
end
else // If it doesn't start with "<", it is a plain text node
begin
ElementType := EtText;
while True do
begin
if CharInSet(sc.CurrentChar, [#0, '<']) then
Break;
sc.JumpToNextChar;
end;
tmp := sc.subStr(OldCodeIndex, sc.CharIndex - OldCodeIndex);
end;
//
// ShowMessage(sc.subStr(30));
case ElementType of
EtUnknow:
begin
DoError('LineNum:' + IntToStr(BeginLineNum) + 'Unparseable content:' +
sc.subStr(100));
end;
EtDocType:
begin
Tag := CreateDocTypeElement(nil, tmp, BeginLineNum, BeginColNum);
AElementList.Add(Tag);
end;
EtTag:
begin
Tag := CreateTagElement(nil, tmp, BeginLineNum, BeginColNum);
AElementList.Add(Tag);
//
if (UpperCase(Tag.FTagName) = 'SCRIPT') and (not Tag.FIsCloseTag) and
(not Tag.FClosed) then
begin
// read script
BeginLineNum := sc.LineNum;
BeginColNum := sc.ColNum;
tmp := ParserScriptData();
Tag := CreateScriptElement(nil, tmp, BeginLineNum, BeginColNum);
AElementList.Add(Tag);
end
else if (UpperCase(Tag.FTagName) = 'STYLE') and (not Tag.FIsCloseTag)
and (not Tag.FClosed) then
begin
// read Style
BeginLineNum := sc.LineNum;
BeginColNum := sc.ColNum;
tmp := ParserStyleData();
Tag := CreateStyleElement(nil, tmp, BeginLineNum, BeginColNum);
AElementList.Add(Tag);
end;
end;
EtText:
begin
Tag := CreateTextElement(nil, tmp, BeginLineNum, BeginColNum);
Tag.FSourceLine := BeginLineNum;
Tag.FSourceCol := BeginColNum;
AElementList.Add(Tag);
end;
EtComment:
begin
Tag := CreateCommentElement(nil, tmp, BeginLineNum, BeginColNum);
Tag.FSourceLine := BeginLineNum;
Tag.FSourceCol := BeginColNum;
AElementList.Add(Tag);
end;
end;
end;
//
//
end;
function BuildTree(ElementList: THtmlElementList): THtmlElement;
var
I, J: Integer;
E: THtmlElement;
T: THtmlElement;
FoundIndex: Integer;
begin
Result := THtmlElement.Create(nil, '', 0, 0);
Result.FTagName := '#DOCUMENT';
Result.FClosed := false;
ElementList.Insert(0, Result);
I := 1;
while I < ElementList.Count do
begin
E := ElementList[I] as THtmlElement;
// TagProperty := GetTagProperty(E.FTagName);
// Empty node, look down, if the next node with Tag is not its closed node, then automatically close
FoundIndex := -1;
if E.FIsCloseTag then
begin
for J := (I - 1) downto 0 do
begin