-
Notifications
You must be signed in to change notification settings - Fork 30
/
Xml.VerySimple.pas
1528 lines (1365 loc) · 48.1 KB
/
Xml.VerySimple.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
{ VerySimpleXML v2.0.5 - a lightweight, one-unit, cross-platform XML reader/writer
for Delphi 2010 - 10.3.2 by Dennis Spreen
http://blog.spreendigital.de/2014/09/13/verysimplexml-2-0/
(c) Copyrights 2011-2019 Dennis D. Spreen <dennis@spreendigital.de>
This unit is free and can be used for any needs. The introduction of
any changes and the use of those changed library is permitted without
limitations. Only requirement:
This text must be present without changes in all modifications of library.
* The contents of this file are used with permission, subject to
* the Mozilla Public License Version 1.1 (the "License"); you may *
* not use this file except in compliance with the License. You may *
* obtain a copy of the License at *
* http: www.mozilla.org/MPL/MPL-1.1.html *
* *
* Software distributed under the License is distributed on an *
* "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or *
* implied. See the License for the specific language governing *
* rights and limitations under the License. *
}
unit Xml.VerySimple;
interface
uses
System.Classes, System.SysUtils, Generics.Defaults, Generics.Collections, System.Rtti;
const
TXmlSpaces = #$20 + #$0A + #$0D + #9;
type
TXmlVerySimple = class;
TXmlNode = class;
TXmlNodeType = (ntElement, ntText, ntCData, ntProcessingInstr, ntComment, ntDocument, ntDocType, ntXmlDecl);
TXmlNodeTypes = set of TXmlNodeType;
TXmlNodeList = class;
TXmlAttributeType = (atValue, atSingle);
TXmlOptions = set of (doNodeAutoIndent, doCompact, doParseProcessingInstr, doPreserveWhiteSpace, doCaseInsensitive,
doWriteBOM);
TExtractTextOptions = set of (etoDeleteStopChar, etoStopString);
{$IFNDEF AUTOREFCOUNT}
WeakAttribute = class(TCustomAttribute);
{$ENDIF}
TStreamReaderFillBuffer = procedure(var Encoding: TEncoding) of object;
TXmlStreamReader = class(TStreamReader)
protected
FBufferedData: TStringBuilder;
FNoDataInStream: PBoolean;
FFillBuffer: TStreamReaderFillBuffer;
procedure FillBuffer;
/// <summary> Call to FillBuffer method of TStreamreader </summary>
public
/// <summary> Extend the TStreamReader with RTTI pointers </summary>
constructor Create(Stream: TStream; Encoding: TEncoding; DetectBOM: Boolean = False; BufferSize: Integer = 4096);
/// <summary> Assures the read buffer holds at least Value characters </summary>
function PrepareBuffer(Value: Integer): Boolean;
/// <summary> Extract text until chars found in StopChars </summary>
function ReadText(const StopChars: String; Options: TExtractTextOptions): String; virtual;
/// <summary> Returns fist char but does not removes it from the buffer </summary>
function FirstChar: String;
/// <summary> Proceed with the next character(s) (value optional, default 1) </summary>
procedure IncCharPos(Value: Integer = 1); virtual;
/// <summary> Returns True if the first uppercased characters at the current position match Value </summary>
function IsUppercaseText(const Value: String): Boolean; virtual;
end;
TXmlAttribute = class(TObject)
private
FValue: String;
protected
procedure SetValue(const Value: String); virtual;
public
/// <summary> Attribute name </summary>
Name: String;
/// <summary> Attributes without values are set to atSingle, else to atValue </summary>
AttributeType: TXmlAttributeType;
/// <summary> Create a new attribute </summary>
constructor Create; virtual;
/// <summary> Return the attribute as a String </summary>
function AsString: String;
/// <summary> Escapes XML control characters </summar>
class function Escape(const Value: String): String; virtual;
/// <summary> Assign attribute values from source attribute </summary>
procedure Assign(Source: TXmlAttribute); virtual;
/// <summary> Attribute value (always a String) </summary>
property Value: String read FValue write SetValue;
end;
TXmlAttributeList = class(TObjectList<TXmlAttribute>)
public
/// <summary> The xml document of the attribute list of the node</summary>
[Weak] Document: TXmlVerySimple;
/// <summary> Add a name only attribute </summary>
function Add(const Name: String): TXmlAttribute; overload; virtual;
/// <summary> Returns the attribute given by name (case insensitive), NIL if no attribute found </summary>
function Find(const Name: String): TXmlAttribute; virtual;
/// <summary> Deletes an attribute given by name (case insensitive) </summary>
procedure Delete(const Name: String); overload; virtual;
/// <summary> Returns True if an attribute with the given name is found (case insensitive) </summary>
function HasAttribute(const AttrName: String): Boolean; virtual;
/// <summary> Returns the attributes in string representation </summary>
function AsString: String; virtual;
/// <summary> Clears current attributes and assigns all attributes from source attributes </summary>
procedure Assign(Source: TXmlAttributeList); virtual;
end;
TXmlNode = class(TObject)
protected
[Weak] FDocument: TXmlVerySimple;
procedure SetDocument(Value: TXmlVerySimple);
function GetAttr(const AttrName: String): String; virtual;
procedure SetAttr(const AttrName: String; const AttrValue: String); virtual;
public
/// <summary> All attributes of the node </summary>
AttributeList: TXmlAttributeList;
/// <summary> List of child nodes, never NIL </summary>
ChildNodes: TXmlNodeList;
/// <summary> Name of the node </summary>
Name: String; // Node name
/// <summary> The node type, see TXmlNodeType </summary>
NodeType: TXmlNodeType;
/// <summary> Parent node, may be NIL </summary>
[Weak] Parent: TXmlNode;
/// <summary> Text value of the node </summary>
Text: String;
/// <summary> Creates a new XML node </summary>
constructor Create(ANodeType: TXmlNodeType = ntElement); virtual;
/// <summary> Removes the node from its parent and frees all of its childs </summary>
destructor Destroy; override;
/// <summary> Clears the attributes, the text and all of its child nodes (but not the name) </summary>
procedure Clear;
/// <summary> Find a child node by its name </summary>
function Find(const Name: String; NodeTypes: TXmlNodeTypes = [ntElement]): TXmlNode; overload; virtual;
/// <summary> Find a child node by name and attribute name </summary>
function Find(const Name, AttrName: String; NodeTypes: TXmlNodeTypes = [ntElement]): TXmlNode; overload; virtual;
/// <summary> Find a child node by name, attribute name and attribute value </summary>
function Find(const Name, AttrName, AttrValue: String; NodeTypes: TXmlNodeTypes = [ntElement]): TXmlNode; overload; virtual;
/// <summary> Return a list of child nodes with the given name and (optional) node types </summary>
function FindNodes(const Name: String; NodeTypes: TXmlNodeTypes = [ntElement]): TXmlNodeList; virtual;
/// <summary> Returns True if the attribute exists </summary>
function HasAttribute(const AttrName: String): Boolean; virtual;
/// <summary> Returns True if a child node with that name exits </summary>
function HasChild(const Name: String; NodeTypes: TXmlNodeTypes = [ntElement]): Boolean; virtual;
/// <summary> Add a child node with an optional NodeType (default: ntElement)</summary>
function AddChild(const AName: String; ANodeType: TXmlNodeType = ntElement): TXmlNode; virtual;
/// <summary> Insert a child node at a specific position with a (optional) NodeType (default: ntElement)</summary>
function InsertChild(const Name: String; Position: Integer; NodeType: TXmlNodeType = ntElement): TXmlNode; virtual;
/// <summary> Fluent interface for setting the text of the node </summary>
function SetText(const Value: String): TXmlNode; virtual;
/// <summary> Fluent interface for setting the node attribute given by attribute name and attribute value </summary>
function SetAttribute(const AttrName, AttrValue: String): TXmlNode; virtual;
/// <summary> Returns first child or NIL if there aren't any child nodes </summary>
function FirstChild: TXmlNode; virtual;
/// <summary> Returns last child node or NIL if there aren't any child nodes </summary>
function LastChild: TXmlNode; virtual;
/// <summary> Returns next sibling </summary>
function NextSibling: TXmlNode; overload; virtual;
/// <summary> Returns previous sibling </summary>
function PreviousSibling: TXmlNode; overload; virtual;
/// <summary> Returns True if the node has at least one child node </summary>
function HasChildNodes: Boolean; virtual;
/// <summary> Returns True if the node has a text content and no child nodes </summary>
function IsTextElement: Boolean; virtual;
/// <summary> Fluent interface for setting the node type </summary>
function SetNodeType(Value: TXmlNodeType): TXmlNode; virtual;
/// <summary> Attributes of a node, accessible by attribute name (case insensitive) </summary>
property Attributes[const AttrName: String]: String read GetAttr write SetAttr;
/// <summary> The xml document of the node </summary>
property Document: TXmlVerySimple read FDocument write SetDocument;
/// <summary> The node name, same as property Name </summary>
property NodeName: String read Name write Name;
/// <summary> The node text, same as property Text </summary>
property NodeValue: String read Text write Text;
end;
TXmlNodeList = class(TObjectList<TXmlNode>)
protected
function IsSame(const Value1, Value2: String): Boolean; virtual;
public
/// <summary> The xml document of the node list </summary>
[Weak] Document: TXmlVerySimple;
/// <summary> The parent node of the node list </summary>
[Weak] Parent: TXmlNode;
/// <summary> Adds a node and sets the parent of the node to the parent of the list </summary>
function Add(Value: TXmlNode): Integer; overload; virtual;
/// <summary> Creates a new node of type NodeType (default ntElement) and adds it to the list </summary>
function Add(NodeType: TXmlNodeType = ntElement): TXmlNode; overload; virtual;
/// <summary> Add a child node with an optional NodeType (default: ntElement)</summary>
function Add(const Name: String; NodeType: TXmlNodeType = ntElement): TXmlNode; overload; virtual;
/// <summary> Find a node by its name (case sensitive), returns NIL if no node is found </summary>
function Find(const Name: String; NodeTypes: TXmlNodeTypes = [ntElement]): TXmlNode; overload; virtual;
/// <summary> Same as Find(), returnsa a node by its name (case sensitive) </summary>
function FindNode(const Name: String; NodeTypes: TXmlNodeTypes = [ntElement]): TXmlNode; virtual;
/// <summary> Find a node that has the the given attribute, returns NIL if no node is found </summary>
function Find(const Name, AttrName: String; NodeTypes: TXmlNodeTypes = [ntElement]): TXmlNode; overload; virtual;
/// <summary> Find a node that as the given attribute name and value, returns NIL otherwise </summary>
function Find(const Name, AttrName, AttrValue: String; NodeTypes: TXmlNodeTypes = [ntElement]): TXmlNode; overload; virtual;
/// <summary> Return a list of child nodes with the given name and (optional) node types </summary>
function FindNodes(const Name: String; NodeTypes: TXmlNodeTypes = [ntElement]): TXmlNodeList; virtual;
/// <summary> Returns True if the list contains a node with the given name </summary>
function HasNode(const Name: String; NodeTypes: TXmlNodeTypes = [ntElement]): Boolean; virtual;
/// <summary> Inserts a node at the given position </summary>
function Insert(const Name: String; Position: Integer; NodeType: TXmlNodeType = ntElement): TXmlNode; overload; virtual;
/// <summary> Returns the first child node, same as .First </summary>
function FirstChild: TXmlNode; virtual;
/// <summary> Returns next sibling node </summary>
function NextSibling(Node: TXmlNode): TXmlNode; virtual;
/// <summary> Returns previous sibling node </summary>
function PreviousSibling(Node: TXmlNode): TXmlNode; virtual;
/// <summary> Returns the node at the given position </summary>
function Get(Index: Integer): TXmlNode; virtual;
end;
TXmlVerySimple = class(TObject)
protected
Root: TXmlNode;
[Weak] FHeader: TXmlNode;
[Weak] FDocumentElement: TXmlNode;
SkipIndent: Boolean;
procedure Parse(Reader: TXmlStreamReader); virtual;
procedure ParseComment(Reader: TXmlStreamReader; var Parent: TXmlNode); virtual;
procedure ParseDocType(Reader: TXmlStreamReader; var Parent: TXmlNode); virtual;
procedure ParseProcessingInstr(Reader: TXmlStreamReader; var Parent: TXmlNode); virtual;
procedure ParseCData(Reader: TXmlStreamReader; var Parent: TXmlNode); virtual;
procedure ParseText(const Line: String; Parent: TXmlNode); virtual;
function ParseTag(Reader: TXmlStreamReader; ParseText: Boolean; var Parent: TXmlNode): TXmlNode; overload; virtual;
function ParseTag(const TagStr: String; var Parent: TXmlNode): TXmlNode; overload; virtual;
procedure Walk(Writer: TStreamWriter; const PrefixNode: String; Node: TXmlNode); virtual;
procedure SetText(const Value: String); virtual;
function GetText: String; virtual;
procedure SetEncoding(const Value: String); virtual;
function GetEncoding: String; virtual;
procedure SetVersion(const Value: String); virtual;
function GetVersion: String; virtual;
procedure Compose(Writer: TStreamWriter); virtual;
procedure SetStandAlone(const Value: String); virtual;
function GetStandAlone: String; virtual;
function GetChildNodes: TXmlNodeList; virtual;
procedure CreateHeaderNode; virtual;
function ExtractText(var Line: String; const StopChars: String; Options: TExtractTextOptions): String; virtual;
procedure SetDocumentElement(Value: TXMlNode); virtual;
procedure SetPreserveWhitespace(Value: Boolean);
function GetPreserveWhitespace: Boolean;
function IsSame(const Value1, Value2: String): Boolean;
public
/// <summary> Indent used for the xml output </summary>
NodeIndentStr: String;
/// <summary> LineBreak used for the xml output, default set to sLineBreak which is OS dependent </summary>
LineBreak: String;
/// <summary> Options for xml output like indentation type </summary>
Options: TXmlOptions;
/// <summary> Creates a new XML document parser </summary>
constructor Create; virtual;
/// <summary> Destroys the XML document parser </summary>
destructor Destroy; override;
/// <summary> Deletes all nodes </summary>
procedure Clear; virtual;
/// <summary> Adds a new node to the document, if it's the first ntElement then sets it as .DocumentElement </summary>
function AddChild(const Name: String; NodeType: TXmlNodeType = ntElement): TXmlNode; virtual;
/// <summary> Creates a new node but doesn't adds it to the document nodes </summary>
function CreateNode(const Name: String; NodeType: TXmlNodeType = ntElement): TXmlNode; virtual;
/// <summary> Escapes XML control characters </summar>
class function Escape(const Value: String): String; virtual;
/// <summary> Translates escaped characters back into XML control characters </summar>
class function Unescape(const Value: String): String; virtual;
/// <summary> Loads the XML from a file </summary>
function LoadFromFile(const FileName: String; BufferSize: Integer = 4096): TXmlVerySimple; virtual;
/// <summary> Loads the XML from a stream </summary>
function LoadFromStream(const Stream: TStream; BufferSize: Integer = 4096): TXmlVerySimple; virtual;
/// <summary> Parse attributes into the attribute list for a given string </summary>
procedure ParseAttributes(const AttribStr: String; AttributeList: TXmlAttributeList); virtual;
/// <summary> Saves the XML to a file </summary>
function SaveToFile(const FileName: String): TXmlVerySimple; virtual;
/// <summary> Saves the XML to a stream, the encoding is specified in the .Encoding property </summary>
function SaveToStream(const Stream: TStream): TXmlVerySimple; virtual;
/// <summary> A list of all root nodes of the document </summary>
property ChildNodes: TXmlNodeList read GetChildNodes;
/// <summary> Returns the first element node </summary>
property DocumentElement: TXmlNode read FDocumentElement write SetDocumentElement;
/// <summary> Specifies the encoding of the XML file, anything else then 'utf-8' is considered as ANSI </summary>
property Encoding: String read GetEncoding write SetEncoding;
/// <summary> XML declarations are stored in here as Attributes </summary>
property Header: TXmlNode read FHeader;
/// <summary> Set to True if all spaces and linebreaks should be included as a text node, same as doPreserve option </summary>
property PreserveWhitespace: Boolean read GetPreserveWhitespace write SetPreserveWhitespace;
/// <summary> Defines the xml declaration property "StandAlone", set it to "yes" or "no" </summary>
property StandAlone: String read GetStandAlone write SetStandAlone;
/// <summary> The XML as a string representation </summary>
property Text: String read GetText write SetText;
/// <summary> Defines the xml declaration property "Version", default set to "1.0" </summary>
property Version: String read GetVersion write SetVersion;
/// <summary> The XML as a string representation, same as .Text </summary>
property Xml: String read GetText write SetText;
end;
implementation
uses
System.StrUtils;
type
TStreamReaderHelper = class helper for TStreamReader
public
procedure GetFillBuffer(var Method: TStreamReaderFillBuffer);
end;
const
{$IF CompilerVersion >= 24} // Delphi XE3+ can use Low(), High() and TEncoding.ANSI
LowStr = Low(String); // Get string index base, may be 0 (NextGen compiler) or 1 (standard compiler)
{$ELSE} // For any previous Delphi version overwrite High() function and use 1 as string index base
LowStr = 1; // Use 1 as string index base
function High(const Value: String): Integer; inline;
begin
Result := Length(Value);
end;
//Delphi XE3 added PosEx as an overloaded Pos function, so we need to wrap it in every other Delphi version
function Pos(const SubStr, S: string; Offset: Integer): Integer; overload; Inline;
begin
Result := PosEx(SubStr, S, Offset);
end;
{$IFEND}
{$IF CompilerVersion < 23} //Delphi XE2 added ANSI as Encoding, in every other Delphi version use TEncoding.Default
type
TEncodingHelper = class helper for TEncoding
class function GetANSI: TEncoding; static;
class property ANSI: TEncoding read GetANSI;
end;
class function TEncodingHelper.GetANSI: TEncoding;
begin
Result := TEncoding.Default;
end;
{$IFEND}
{ TVerySimpleXml }
function TXmlVerySimple.AddChild(const Name: String; NodeType: TXmlNodeType = ntElement): TXmlNode;
begin
Result := CreateNode(Name, NodeType);
if (NodeType = ntElement) and (not Assigned(FDocumentElement)) then
FDocumentElement := Result;
try
Root.ChildNodes.Add(Result);
except
Result.Free;
raise;
end;
Result.Document := Self;
end;
procedure TXmlVerySimple.Clear;
begin
FDocumentElement := NIL;
FHeader := NIL;
Root.Clear;
end;
constructor TXmlVerySimple.Create;
begin
inherited;
Root := TXmlNode.Create;
Root.NodeType := ntDocument;
Root.Parent := Root;
Root.Document := Self;
NodeIndentStr := ' ';
Options := [doNodeAutoIndent, doWriteBOM];
LineBreak := sLineBreak;
CreateHeaderNode;
end;
procedure TXmlVerySimple.CreateHeaderNode;
begin
if Assigned(FHeader) then
Exit;
FHeader := Root.ChildNodes.Insert('xml', 0, ntXmlDecl);
FHeader.Attributes['version'] := '1.0'; // Default XML version
FHeader.Attributes['encoding'] := 'utf-8';
end;
function TXmlVerySimple.CreateNode(const Name: String; NodeType: TXmlNodeType): TXmlNode;
begin
Result := TXmlNode.Create(NodeType);
Result.Name := Name;
Result.Document := Self;
end;
destructor TXmlVerySimple.Destroy;
begin
Root.Parent := NIL;
Root.Clear;
Root.Free;
inherited;
end;
function TXmlVerySimple.GetChildNodes: TXmlNodeList;
begin
Result := Root.ChildNodes;
end;
function TXmlVerySimple.GetEncoding: String;
begin
if Assigned(FHeader) then
Result := FHeader.Attributes['encoding']
else
Result := '';
end;
function TXmlVerySimple.GetPreserveWhitespace: Boolean;
begin
Result := doPreserveWhitespace in Options;
end;
function TXmlVerySimple.GetStandAlone: String;
begin
if Assigned(FHeader) then
Result := FHeader.Attributes['standalone']
else
Result := '';
end;
function TXmlVerySimple.GetVersion: String;
begin
if Assigned(FHeader) then
Result := FHeader.Attributes['version']
else
Result := '';
end;
function TXmlVerySimple.IsSame(const Value1, Value2: String): Boolean;
begin
if doCaseInsensitive in Options then
Result := AnsiSameText(Value1, Value2)
else
Result := (Value1 = Value2);
end;
function TXmlVerySimple.GetText: String;
var
Stream: TStringStream;
begin
if AnsiSameText(Encoding, 'utf-8') then
Stream := TStringStream.Create('', TEncoding.UTF8)
else
Stream := TStringStream.Create('', TEncoding.ANSI);
try
SaveToStream(Stream);
Result := Stream.DataString;
finally
Stream.Free;
end;
end;
procedure TXmlVerySimple.Compose(Writer: TStreamWriter);
var
Child: TXmlNode;
begin
if doCompact in Options then
begin
Writer.NewLine := '';
LineBreak := '';
end
else
Writer.NewLine := LineBreak;
SkipIndent := False;
for Child in Root.ChildNodes do
Walk(Writer, '', Child);
end;
function TXmlVerySimple.LoadFromFile(const FileName: String; BufferSize: Integer = 4096): TXmlVerySimple;
var
Stream: TFileStream;
begin
Stream := TFileStream.Create(FileName, fmOpenRead + fmShareDenyWrite);
try
LoadFromStream(Stream, BufferSize);
finally
Stream.Free;
end;
Result := Self;
end;
function TXmlVerySimple.LoadFromStream(const Stream: TStream; BufferSize: Integer = 4096): TXmlVerySimple;
var
Reader: TXmlStreamReader;
begin
if Encoding = '' then // none specified then use UTF8 with DetectBom
Reader := TXmlStreamReader.Create(Stream, TEncoding.UTF8, True, BufferSize)
else
if AnsiSameText(Encoding, 'utf-8') then
Reader := TXmlStreamReader.Create(Stream, TEncoding.UTF8, False, BufferSize)
else
Reader := TXmlStreamReader.Create(Stream, TEncoding.ANSI, False, BufferSize);
try
Parse(Reader);
finally
Reader.Free;
end;
Result := Self;
end;
procedure TXmlVerySimple.Parse(Reader: TXmlStreamReader);
var
Parent, Node: TXmlNode;
FirstChar: String;
ALine: String;
begin
Clear;
Parent := Root;
while not Reader.EndOfStream do
begin
ALine := Reader.ReadText('<', [etoDeleteStopChar]);
if ALine <> '' then // Check for text nodes
begin
ParseText(Aline, Parent);
if Reader.EndOfStream then // if no chars available then exit
Break;
end;
FirstChar := Reader.FirstChar;
if FirstChar = '!' then
if Reader.IsUppercaseText('!--') then // check for a comment node
ParseComment(Reader, Parent)
else
if Reader.IsUppercaseText('!DOCTYPE') then // check for a doctype node
ParseDocType(Reader, Parent)
else
if Reader.IsUppercaseText('![CDATA[') then // check for a cdata node
ParseCData(Reader, Parent)
else
ParseTag(Reader, False, Parent) // try to parse as tag
else // Check for XML header / processing instructions
if FirstChar = '?' then // could be header or processing instruction
ParseProcessingInstr(Reader, Parent)
else
if FirstChar <> '' then
begin // Parse a tag, the first tag in a document is the DocumentElement
Node := ParseTag(Reader, True, Parent);
if (not Assigned(FDocumentElement)) and (Parent = Root) then
FDocumentElement := Node;
end;
end;
end;
procedure TXmlVerySimple.ParseAttributes(const AttribStr: String; AttributeList: TXmlAttributeList);
var
Attribute: TXmlAttribute;
AttrName, AttrText: String;
Quote: String;
Value: String;
begin
Value := TrimLeft(AttribStr);
while Value <> '' do
begin
AttrName := ExtractText(Value, ' =', []);
Value := TrimLeft(Value);
Attribute := AttributeList.Add(AttrName);
if (Value = '') or (Value[LowStr]<>'=') then
Continue;
Delete(Value, 1, 1);
Attribute.AttributeType := atValue;
ExtractText(Value, '''' + '"', []);
Value := TrimLeft(Value);
if Value <> '' then
begin
Quote := Value[LowStr];
Delete(Value, 1, 1);
AttrText := ExtractText(Value, Quote, [etoDeleteStopChar]); // Get Attribute Value
Attribute.Value := Unescape(AttrText);
Value := TrimLeft(Value);
end;
end;
end;
procedure TXmlVerySimple.ParseText(const Line: String; Parent: TXmlNode);
var
SingleChar: Char;
Node: TXmlNode;
TextNode: Boolean;
begin
if PreserveWhiteSpace then
TextNode := True
else
begin
TextNode := False;
for SingleChar in Line do
if AnsiStrScan(TXmlSpaces, SingleChar) = NIL then
begin
TextNode := True;
Break;
end;
end;
if TextNode then
begin
Node := Parent.ChildNodes.Add(ntText);
Node.Text := Line;
end;
end;
procedure TXmlVerySimple.ParseCData(Reader: TXmlStreamReader; var Parent: TXmlNode);
var
Node: TXmlNode;
begin
Node := Parent.ChildNodes.Add(ntCData);
Node.Text := Reader.ReadText(']]>', [etoDeleteStopChar, etoStopString]);
end;
procedure TXmlVerySimple.ParseComment(Reader: TXmlStreamReader; var Parent: TXmlNode);
var
Node: TXmlNode;
begin
Node := Parent.ChildNodes.Add(ntComment);
Node.Text := Reader.ReadText('-->', [etoDeleteStopChar, etoStopString]);
end;
procedure TXmlVerySimple.ParseDocType(Reader: TXmlStreamReader; var Parent: TXmlNode);
var
Node: TXmlNode;
Quote: String;
begin
Node := Parent.ChildNodes.Add(ntDocType);
Node.Text := Reader.ReadText('>[', []);
if not Reader.EndOfStream then
begin
Quote := Reader.FirstChar;
Reader.IncCharPos;
if Quote = '[' then
Node.Text := Node.Text + Quote + Reader.ReadText(']',[etoDeleteStopChar]) + ']' +
Reader.ReadText('>', [etoDeleteStopChar]);
end;
end;
procedure TXmlVerySimple.ParseProcessingInstr(Reader: TXmlStreamReader; var Parent: TXmlNode);
var
Node: TXmlNode;
Tag: String;
begin
Reader.IncCharPos; // omit the '?'
Tag := Reader.ReadText('?>', [etoDeleteStopChar, etoStopString]);
Node := ParseTag(Tag, Parent);
if lowercase(Node.Name) = 'xml' then
begin
FHeader := Node;
FHeader.NodeType := ntXmlDecl;
end
else
begin
Node.NodeType := ntProcessingInstr;
if not (doParseProcessingInstr in Options) then
begin
Node.Text := Tag;
Node.AttributeList.Clear;
end;
end;
Parent := Node.Parent;
end;
function TXmlVerySimple.ParseTag(Reader: TXmlStreamReader; ParseText: Boolean; var Parent: TXmlNode): TXmlNode;
var
Tag: String;
ALine: String;
SingleChar: Char;
begin
Tag := Reader.ReadText('>', [etoDeleteStopChar]);
Result := ParseTag(Tag, Parent);
if (Result = Parent) and (ParseText) then // only non-self closing nodes may have a text
begin
ALine := Reader.ReadText('<', []);
ALine := Unescape(ALine);
if PreserveWhiteSpace then
Result.Text := ALine
else
for SingleChar in ALine do
if AnsiStrScan(TXmlSpaces, SingleChar) = NIL then
begin
Result.Text := ALine;
Break;
end;
end;
end;
function TXmlVerySimple.ParseTag(const TagStr: String; var Parent: TXmlNode): TXmlNode;
var
Node: TXmlNode;
ALine: String;
CharPos: Integer;
Tag: String;
begin
// A closing tag does not have any attributes nor text
if (TagStr <> '') and (TagStr[LowStr] = '/') then
begin
Result := Parent;
Parent := Parent.Parent;
Exit;
end;
// Creat a new new ntElement node
Node := Parent.ChildNodes.Add;
Result := Node;
Tag := TagStr;
// Check for a self-closing Tag (does not have any text)
if (Tag <> '') and (Tag[High(Tag)] = '/') then
Delete(Tag, Length(Tag), 1)
else
Parent := Node;
CharPos := Pos(' ', Tag);
if CharPos <> 0 then // Tag may have attributes
begin
ALine := Tag;
Delete(Tag, CharPos, Length(Tag));
Delete(ALine, 1, CharPos);
if ALine <> '' then
ParseAttributes(ALine, Node.AttributeList);
end;
Node.Name := Tag;
end;
function TXmlVerySimple.SaveToFile(const FileName: String): TXmlVerySimple;
var
Stream: TFileStream;
begin
Stream := TFileStream.Create(FileName, fmCreate);
try
SaveToStream(Stream);
finally
Stream.Free;
end;
Result := Self;
end;
function TXmlVerySimple.SaveToStream(const Stream: TStream): TXmlVerySimple;
var
Writer: TStreamWriter;
begin
if AnsiSameText(Self.Encoding, 'utf-8') then
if doWriteBOM in Options then
Writer := TStreamWriter.Create(Stream, TEncoding.UTF8)
else
Writer := TStreamWriter.Create(Stream)
else
Writer := TStreamWriter.Create(Stream, TEncoding.ANSI);
try
Compose(Writer);
finally
Writer.Free;
end;
Result := Self;
end;
procedure TXmlVerySimple.SetDocumentElement(Value: TXMlNode);
begin
FDocumentElement := Value;
if Value.Parent = NIL then
Root.ChildNodes.Add(Value);
end;
procedure TXmlVerySimple.SetEncoding(const Value: String);
begin
CreateHeaderNode;
FHeader.Attributes['encoding'] := Value;
end;
procedure TXmlVerySimple.SetPreserveWhitespace(Value: Boolean);
begin
if Value then
Options := Options + [doPreserveWhitespace]
else
Options := Options - [doPreserveWhitespace]
end;
procedure TXmlVerySimple.SetStandAlone(const Value: String);
begin
CreateHeaderNode;
FHeader.Attributes['standalone'] := Value;
end;
procedure TXmlVerySimple.SetVersion(const Value: String);
begin
CreateHeaderNode;
FHeader.Attributes['version'] := Value;
end;
class function TXmlVerySimple.Unescape(const Value: String): String;
begin
Result := ReplaceStr(Value, '<', '<');
Result := ReplaceStr(Result, '>', '>');
Result := ReplaceStr(Result, '"', '"');
Result := ReplaceStr(Result, ''', '''');
Result := ReplaceStr(Result, '&', '&');
end;
procedure TXmlVerySimple.SetText(const Value: String);
var
Stream: TStringStream;
begin
Stream := TStringStream.Create('', TEncoding.UTF8);
try
Stream.WriteString(Value);
Stream.Position := 0;
LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
procedure TXmlVerySimple.Walk(Writer: TStreamWriter; const PrefixNode: String; Node: TXmlNode);
var
Child: TXmlNode;
Line: String;
Indent: String;
begin
if (Node = Root.ChildNodes.First) or (SkipIndent) then
begin
Line := '<';
SkipIndent := False;
end
else
Line := LineBreak + PrefixNode + '<';
case Node.NodeType of
ntComment:
begin
Writer.Write(Line + '!--' + Node.Text + '-->');
Exit;
end;
ntDocType:
begin
Writer.Write(Line + '!DOCTYPE ' + Node.Text + '>');
Exit;
end;
ntCData:
begin
Writer.Write('<![CDATA[' + Node.Text + ']]>');
Exit;
end;
ntText:
begin
Writer.Write(Node.Text);
SkipIndent := True;
Exit;
end;
ntProcessingInstr:
begin
if Node.AttributeList.Count > 0 then
Writer.Write(Line + '?' + Node.Name + Node.AttributeList.AsString + '?>')
else
Writer.Write(Line + '?' + Node.Text + '?>');
Exit;
end;
ntXmlDecl:
begin
Writer.Write(Line + '?' + Node.Name + Node.AttributeList.AsString + '?>');
Exit;
end;
end;
Line := Line + Node.Name + Node.AttributeList.AsString;
// Self closing tags
if (Node.Text = '') and (not Node.HasChildNodes) then
begin
Writer.Write(Line + '/>');
Exit;
end;
Line := Line + '>';
if Node.Text <> '' then
begin
Line := Line + Escape(Node.Text);
if Node.HasChildNodes then
SkipIndent := True;
end;
Writer.Write(Line);
// Set indent for child nodes
if doCompact in Options then
Indent := ''
else
Indent := PrefixNode + NodeIndentStr;
// Process child nodes
for Child in Node.ChildNodes do
Walk(Writer, Indent, Child);
// If node has child nodes and last child node is not a text node then set indent for closing tag
if (Node.HasChildNodes) and (not SkipIndent) then
Indent := LineBreak + PrefixNode
else
Indent := '';
Writer.Write(Indent + '</' + Node.Name + '>');
end;
class function TXmlVerySimple.Escape(const Value: String): String;
begin
Result := TXmlAttribute.Escape(Value);
Result := ReplaceStr(Result, '''', ''');
end;
function TXmlVerySimple.ExtractText(var Line: String; const StopChars: String;
Options: TExtractTextOptions): String;
var
CharPos, FoundPos: Integer;
TestChar: Char;
begin
FoundPos := 0;
for TestChar in StopChars do
begin
CharPos := Pos(TestChar, Line);
if (CharPos <> 0) and ((FoundPos = 0) or (CharPos < FoundPos)) then
FoundPos := CharPos;
end;
if FoundPos <> 0 then
begin
Dec(FoundPos);
Result := Copy(Line, 1, FoundPos);
if etoDeleteStopChar in Options then
Inc(FoundPos);
Delete(Line, 1, FoundPos);
end
else
begin
Result := Line;
Line := '';
end;
end;
{ TXmlNode }
function TXmlNode.AddChild(const AName: String; ANodeType: TXmlNodeType = ntElement): TXmlNode;
begin
Result := ChildNodes.Add(AName, ANodeType);
end;
procedure TXmlNode.Clear;
begin
Text := '';
AttributeList.Clear;
ChildNodes.Clear;
end;
constructor TXmlNode.Create(ANodeType: TXmlNodeType = ntElement);
begin
ChildNodes := TXmlNodeList.Create;
ChildNodes.Parent := Self;
AttributeList := TXmlAttributeList.Create;
NodeType := ANodeType;
end;
destructor TXmlNode.Destroy;
begin
Clear;
ChildNodes.Free;
AttributeList.Free;
inherited;
end;
function TXmlNode.Find(const Name: String; NodeTypes: TXmlNodeTypes = [ntElement]): TXmlNode;
begin
Result := ChildNodes.Find(Name, NodeTypes);
end;
function TXmlNode.Find(const Name, AttrName, AttrValue: String; NodeTypes: TXmlNodeTypes = [ntElement]): TXmlNode;
begin
Result := ChildNodes.Find(Name, AttrName, AttrValue, NodeTypes);
end;
function TXmlNode.Find(const Name, AttrName: String; NodeTypes: TXmlNodeTypes = [ntElement]): TXmlNode;
begin
Result := ChildNodes.Find(Name, AttrName, NodeTypes);
end;
function TXmlNode.FindNodes(const Name: String; NodeTypes: TXmlNodeTypes = [ntElement]): TXmlNodeList;
begin
Result := ChildNodes.FindNodes(Name, NodeTypes);
end;
function TXmlNode.FirstChild: TXmlNode;