-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathNeslib.Xml.IO.pas
1241 lines (1059 loc) · 31.4 KB
/
Neslib.Xml.IO.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 Neslib.Xml.IO;
{< Classes for reading and writing XML. }
{$INCLUDE 'Neslib.inc'}
interface
uses
System.Classes,
System.SysUtils,
Neslib.Collections,
Neslib.Xml.Types;
type
{ Options to customize XML reading }
TXmlReaderOption = (
{ Allow unknown named character references. These are named character
references other than the standard & ' < > and "
ones.
If set, unknown character references will be parsed as-is. }
AllowUnknownNamedCharacterReferences);
TXmlReaderOptions = set of TXmlReaderOption;
type
{ The current state of an IXmlReader. }
TXmlReaderState = (
{ The end of the XML stream has been reached. }
EndOfStream,
{ The reader is positioned at the start of an element (eg. <elem>). }
StartElement,
{ The reader is positioned at the end of an element (eg. </elem>). }
EndElement,
{ The reader is positioned at the text within an element (eg. the text
'foo' in this example: <elem>foo</elem>) }
Text,
{ The reader is positioned at a comment (eg. <!-- Comment -->) or a DTD
definition. }
Comment,
{ The reader is positioned at a CDATA section (eg. <![CDATA[ data ]]>) }
CData);
type
{ Exception type that is raised on parsing errors. }
EXmlParserError = class(Exception)
{$REGION 'Internal Declarations'}
private
FXml: XmlString;
FLineNumber: Integer;
FColumnNumber: Integer;
FPosition: Integer;
function GetColumnNumber: Integer;
function GetLineNumber: Integer;
private
procedure CalcLineAndColumnNumber;
public
constructor Create(const AMsg: String; const AXml: XmlString;
const APosition: Integer);
{$ENDREGION 'Internal Declarations'}
public
{ The line number of the error in the source text, starting at 1. }
property LineNumber: Integer read GetLineNumber;
{ The column number of the error in the source text, starting at 1. }
property ColumnNumber: Integer read GetColumnNumber;
{ The position of the error in the source text, starting at 0.
The position is the offset (in characters) from the beginning of the
text. }
property Position: Integer read FPosition;
end;
type
{ An attribute as read by a TXmlReader }
TXmlReaderAttribute = record
public
{ The index (in the string pool) of the name of the attribute }
NameIndex: Integer;
{ The value of the attribute }
Value: XmlString;
end;
type
{ Class for reading data in XML format. }
TXmlReader = class
{$REGION 'Internal Declarations'}
private
FXml: XmlString;
FValueIndex: Integer;
FValueString: XmlString;
FCurrent: PXmlChar;
FPrev: PXmlChar;
FAttributes: TList<TXmlReaderAttribute>;
FEncoding: TXmlEncoding;
FInternPool: TXmlStringInternPool;
FOptions: TXmlReaderOptions;
FIsEmptyElement: Boolean;
function GetAttributeCount: Integer; //inline;
function GetAttribute(const AIndex: Integer): TXmlReaderAttribute; //inline;
private
function SetValue(const AStart, AEnd: PXmlChar): Boolean;
procedure ParseDeclaration;
procedure ParseStartElement;
procedure ParseEndElement;
procedure ParseComment;
procedure ParseCData;
procedure AddAttribute(const ANameStart, ANameEnd, AValueStart,
AValueEnd: PXmlChar);
protected
constructor Create(const AXml: XmlString; const AEncoding: TXmlEncoding;
const AInternPool: TXmlStringInternPool;
const AOptions: TXmlReaderOptions); overload;
public
destructor Destroy; override;
{$ENDREGION 'Internal Declarations'}
public
{ Creates a reader using a XML formatted string to parse.
Parameters:
AXml: the XML string to parse.
AInternPool: a string intern pool used to store element and attribute
names.
AOptions: (optional) options to customize the reader }
constructor Create(const AXml: XmlString;
const AInternPool: TXmlStringInternPool;
const AOptions: TXmlReaderOptions = []); overload;
{ Creates a reader from a file.
Parameters:
AFilename: the name of the file to load.
AInternPool: a string intern pool used to store element and attribute
names.
AOptions: (optional) options to customize the reader
Returns:
The reader. }
class function Load(const AFilename: String;
const AInternPool: TXmlStringInternPool;
const AOptions: TXmlReaderOptions = []): TXmlReader; overload; static;
{ Creates a reader from a stream.
Parameters:
AStream: the stream to load.
AInternPool: a string intern pool used to store element and attribute
names.
AOptions: (optional) options to customize the reader
Returns:
The reader. }
class function Load(const AStream: TStream;
const AInternPool: TXmlStringInternPool;
const AOptions: TXmlReaderOptions = []): TXmlReader; overload; static;
{ Creates a reader from a byte array.
Parameters:
ABytes: the byte array containing the XML data.
AInternPool: a string intern pool used to store element and attribute
names.
AOptions: (optional) options to customize the reader
Returns:
The reader. }
class function Load(const ABytes: TBytes;
const AInternPool: TXmlStringInternPool;
const AOptions: TXmlReaderOptions = []): TXmlReader; overload; static;
{ Encoding of the source file. }
property Encoding: TXmlEncoding read FEncoding;
public
{ Raises a parse exception.
Parameters:
AMsg: Pointer to a resource string with the error message.
This method is used internally. }
procedure ParseError(const AMsg: PResStringRec);
{ Reads the next piece of data from the XML stream.
Parameters:
AState: is set to the current state of the reader. That is, it indicates
at what kind of data the reader is currently positioned. Depending
on AState, you use one of the properties to get the details.
Returns:
True if more data is available, or False if the end of the stream has
been reached.
Raises:
EXmlParserError if the XML data is invalid. }
function Next(out AState: TXmlReaderState): Boolean;
(*** The value of these properties depend on the AState argument returned
by the Next function ***)
{ Whether the element is an empty element, as in <elem />.
Only valid for TXmlReaderState.StartElement. }
property IsEmptyElement: Boolean read FIsEmptyElement;
{ Index of the currently parsed value in the string intern pool, depending
on the state:
* TXmlReaderState.StartElement/EndElement: index of the name of the
element.
* Otherwise: not used }
property ValueIndex: Integer read FValueIndex;
{ The currently parsed value, depending on the state:
* TXmlReaderState.StartElement/EndElement: not used.
* TXmlReaderState.Text: the text value. Note that text containing only
whitespace is ignored. However, the text may contain leading or
trailing whitespace.
* TXmlReaderState.Comment: the comment.
* TXmlReaderState.CData: the CData value. }
property ValueString: XmlString read FValueString;
{ Number of attributes of the current element.
Only valid for TXmlReaderState.StartElement. }
property AttributeCount: Integer read GetAttributeCount;
{ The attributes of the current element.
Only valid for TXmlReaderState.StartElement. }
property Attributes[const AIndex: Integer]: TXmlReaderAttribute read GetAttribute;
end;
type
{ A helper class for writing XML data. }
TXmlWriter = class
{$REGION 'Internal Declarations'}
private const
INDENT_SIZE = 2;
private
FBuffer: PByte;
FSize: Integer;
FCapacity: Integer;
FIndentString: XmlString;
FLineBreak: XmlChar;
private
procedure Append(const AValue; const ASize: Integer);
{$ENDREGION 'Internal Declarations'}
public
{ Creates a new writer.
Parameters:
AOptions: (optional) XML formatting options.
Defaults to pretty-printing and writing an XML declaration }
constructor Create(const AOptions: TXmlOutputOptions = DEFAULT_XML_OUTPUT_OPTIONS);
destructor Destroy; override;
{ Appends a new-line (#10) to the output if the TXmlOutputOption.Indent
option is set. Otherwise, it doesn't do anything. }
procedure NewLine; inline;
{ Appends an indent to the output if the TXmlOutputOption.Indent option is
set. Otherwise, it doesn't do anything.
Parameters:
ADepth: the indentation depth. Each additional depth adds 2 additional
spaces to the output. }
procedure Indent(const ADepth: Integer);
{ Writes a single character to the output.
Parameters:
AValue: the character to write. }
procedure Write(const AValue: XmlChar); overload; inline;
{ Writes a string (as-is) to the output.
Parameters:
AValue: the string to write.
This method writes the string as-is. If the string can contain reserved
characters (such as '&' and '<'), the use WriteEncoded instead. }
procedure Write(const AValue: XmlString); overload; inline;
{ XML-encodes a string and writes it to the output.
Parameters:
AValue: the string to write.
AForAttribute: (optional) flag indicating whether we are encoding an
attribute (True) or not (False, default). When True, single quotes (')
are not encoded, since the attribute value itself is enclosed in
double quotes (").
This method will replace reseverd characters (such as '&' and '<') to
character entities (eg. '&' and '<'. }
procedure WriteEncoded(const AValue: XmlString;
const AForAttribute: Boolean = False);
{ Writes CData to the output.
Parameters:
ACData: the CData to write.
If ACData contains text that is invalid inside a CData section (such as
']]>'), the only the part until the invalid text is written. }
procedure WriteCData(const ACData: XmlString);
{ Writes a comment to the output.
Parameters:
AComment: the comment to write.
If comment contains text that is invalid inside a comment section (such as
'--'), the only the part until the invalid text is written. }
procedure WriteComment(const AComment: XmlString);
{ Returns the data written (so far) as an XML string. }
function ToXml: XmlString;
{ Returns the data written (so far) as an UTF-8 encoded byte array. }
function ToBytes: TBytes;
end;
resourcestring
{ Error messages that will be raised on parsing errors. }
RS_XML_UNEXPECTED_EOF = 'Unexpected end of XML data.';
RS_XML_CHARACTER_REFERENCE = 'Invalid character reference in XML data.';
RS_XML_INVALID_COMMENT = 'Invalid comment in XML data.';
RS_XML_INVALID_CDATA = 'Invalid CDATA in XML data.';
RS_XML_EQUAL_EXPECTED = 'Expected "=" after XML attribute name.';
RS_XML_INVALID_QUOTE = 'Attribute value must be enclosed in single or double quotes.';
RS_XML_INVALID_END_ELEMENT = 'End element is not allowed here.';
RS_XML_ELEMENT_NAME_MISMATCH = 'Name of end element does not match start element.';
RS_XML_CDATA_NOT_ALLOWED = 'CDATA is not allowed here.';
implementation
uses
System.Character,
Neslib.Utf8;
procedure SwapEndian16(const ASource: Pointer; const ACount: Integer);
begin
var P := PWord(ASource);
for var I := 0 to ACount - 1 do
begin
P^ := (P^ shr 8) or (P^ shl 8);
Inc(P);
end;
end;
procedure SwapEndian32(const ASource: Pointer; const ACount: Integer);
begin
var P := PCardinal(ASource);
for var I := 0 to ACount - 1 do
begin
P^ := (P^ shr 24) or ((P^ and $00FF0000) shr 8) or ((P^ and $0000FF00) shl 8) or (P^ shl 24);
Inc(P);
end;
end;
function Utf32ToUtf16(const ASource: Pointer; const ACount: Integer): String;
begin
SetLength(Result, ACount * 2);
var Src := PCardinal(ASource);
var Dst := PChar(Pointer(Result));
var Start := Dst;
for var I := 0 to ACount - 1 do
begin
if (Src^ >= $00010000) then
begin
Dst^ := Char((((Src^ - $00010000) shr 10) and $000003FF) or $D800);
Inc(Dst);
Dst^ := Char(((Src^ - $00010000) and $000003FF)or $DC00);
Inc(Dst);
end
else
begin
Dst^ := Char(Src^);
Inc(Dst);
end;
Inc(Src);
end;
SetLength(Result, Dst - Start);
end;
{$IFDEF XML_UTF8}
function Utf32ToUtf8(const ASource: Pointer; const ACount: Integer): UTF8String;
begin
var Utf16 := Utf32ToUtf16(ASource, ACount);
Result := Utf16ToUtf8(Utf16);
end;
{$ENDIF}
type
TCharBuffer = record
private const
SIZE = 256;
private type
TBuffer = array [0..SIZE - 1] of XmlChar;
PBuffer = ^TBuffer;
private
FStatic: TBuffer;
FDynamic: PBuffer;
FCurrent: PXmlChar;
FCurrentEnd: PXmlChar;
FDynamicCount: Integer;
public
procedure Initialize; inline;
procedure Release; inline;
procedure Append(const AChar: XmlChar); inline;
function ToString: XmlString; inline;
end;
{ TCharBuffer }
procedure TCharBuffer.Append(const AChar: XmlChar);
begin
if (FCurrent < FCurrentEnd) then
begin
FCurrent^ := AChar;
Inc(FCurrent);
Exit;
end;
ReallocMem(FDynamic, (FDynamicCount + 1) * SizeOf(TBuffer));
FCurrent := PXmlChar(FDynamic) + (FDynamicCount * SIZE);
FCurrentEnd := FCurrent + SIZE;
Inc(FDynamicCount);
FCurrent^ := AChar;
Inc(FCurrent);
end;
procedure TCharBuffer.Initialize;
begin
FDynamic := nil;
FCurrent := @FStatic;
FCurrentEnd := FCurrent + SIZE;
FDynamicCount := 0;
end;
procedure TCharBuffer.Release;
begin
FreeMem(FDynamic);
end;
function TCharBuffer.ToString: XmlString;
begin
if (FDynamic = nil) then
begin
var Start := PXmlChar(@FStatic);
SetString(Result, Start, FCurrent - Start);
Exit;
end;
var TrailingLength := SIZE - (FCurrentEnd - FCurrent);
SetLength(Result, (FDynamicCount * SIZE) + TrailingLength);
Move(FStatic, Result[Low(XmlString)], SizeOf(TBuffer));
var StrIndex := Low(XmlString) + SIZE;
var Src := FDynamic;
for var I := 0 to FDynamicCount - 2 do
begin
Move(Src^, Result[StrIndex], SizeOf(TBuffer));
Inc(Src);
Inc(StrIndex, SIZE);
end;
Move(Src^, Result[StrIndex], TrailingLength * SizeOf(XmlChar));
end;
{ EXmlParserError }
procedure EXmlParserError.CalcLineAndColumnNumber;
begin
var LineNum := 1;
var P := PChar(FXml);
var LineStart := P;
for var I := 0 to FPosition - 1 do
begin
if (P^ = #10) then
begin
Inc(LineNum);
LineStart := P + 1;
end;
Inc(P);
end;
FLineNumber := LineNum;
FColumnNumber := P - LineStart + 1;
end;
constructor EXmlParserError.Create(const AMsg: String; const AXml: XmlString;
const APosition: Integer);
begin
inherited Create(AMsg);
FXml := AXml;
FPosition := APosition;
end;
function EXmlParserError.GetColumnNumber: Integer;
begin
if (FColumnNumber = 0) then
CalcLineAndColumnNumber;
Result := FColumnNumber;
end;
function EXmlParserError.GetLineNumber: Integer;
begin
if (FLineNumber = 0) then
CalcLineAndColumnNumber;
Result := FLineNumber;
end;
{ TXmlReader }
procedure TXmlReader.AddAttribute(const ANameStart, ANameEnd, AValueStart,
AValueEnd: PXmlChar);
var
Attr: TXmlReaderAttribute;
begin
Attr.NameIndex := FInternPool.Get(ANameStart, ANameEnd - ANameStart);
if SetValue(AValueStart, AValueEnd) then
Attr.Value := FValueString
else
Attr.Value := '';
FAttributes.Add(Attr);
end;
constructor TXmlReader.Create(const AXml: XmlString;
const AInternPool: TXmlStringInternPool; const AOptions: TXmlReaderOptions);
begin
Create(AXml, TXmlEncoding.Utf16, AInternPool, AOptions);
end;
constructor TXmlReader.Create(const AXml: XmlString;
const AEncoding: TXmlEncoding; const AInternPool: TXmlStringInternPool;
const AOptions: TXmlReaderOptions);
begin
inherited Create;
FAttributes := TList<TXmlReaderAttribute>.Create;
FXml := AXml;
FEncoding := AEncoding;
FInternPool := AInternPool;
FOptions := AOptions;
FCurrent := PXmlChar(FXml);
end;
destructor TXmlReader.Destroy;
begin
FAttributes.Free;
inherited;
end;
function TXmlReader.GetAttribute(const AIndex: Integer): TXmlReaderAttribute;
begin
Result := FAttributes[AIndex];
end;
function TXmlReader.GetAttributeCount: Integer;
begin
Result := FAttributes.Count;
end;
class function TXmlReader.Load(const AFilename: String;
const AInternPool: TXmlStringInternPool;
const AOptions: TXmlReaderOptions): TXmlReader;
begin
var Stream := TFileStream.Create(AFilename, fmOpenRead or fmShareDenyWrite);
try
Result := Load(Stream, AInternPool, AOptions);
finally
Stream.Free;
end;
end;
class function TXmlReader.Load(const ABytes: TBytes;
const AInternPool: TXmlStringInternPool;
const AOptions: TXmlReaderOptions): TXmlReader;
begin
var Stream := TBytesStream.Create(ABytes);
try
Result := Load(Stream, AInternPool, AOptions);
finally
Stream.Free;
end;
end;
class function TXmlReader.Load(const AStream: TStream;
const AInternPool: TXmlStringInternPool;
const AOptions: TXmlReaderOptions): TXmlReader;
begin
if (AStream = nil) then
Exit(nil);
{ Try to detect encoding from Bom }
var Bom: UInt32 := 0;
var StartPos := AStream.Position;
var Size := AStream.Size - StartPos;
var BomSize: Integer;
var Encoding: TXmlEncoding;
AStream.Read(Bom, 4);
if (Bom = $0000FEFF) then
begin
Encoding := TXmlEncoding.Utf32;
BomSize := 4;
end
else if (Bom = $FFFE0000) then
begin
Encoding := TXmlEncoding.Utf32BigEndian;
BomSize := 4;
end
else if ((Bom and $00FFFFFF) = $00BFBBEF) then
begin
Encoding := TXmlEncoding.Utf8;
BomSize := 3;
end
else if ((Bom and $0000FFFF) = $0000FEFF) then
begin
Encoding := TXmlEncoding.Utf16;
BomSize := 2;
end
else if ((Bom and $0000FFFF) = $0000FFFE) then
begin
Encoding := TXmlEncoding.Utf16BigEndian;
BomSize := 2;
end
else
begin
{ We assume UTF-8 if there is no BOM }
Encoding := TXmlEncoding.Utf8;
BomSize := 0;
end;
Dec(Size, BomSize);
AStream.Position := StartPos + BomSize;
{ We can skip conversion if source encoding matches target encoding }
var Xml: XmlString := '';
{$IFDEF XML_UTF8}
if (Encoding = TXmlEncoding.Utf8) then
begin
SetLength(Xml, Size);
AStream.ReadBuffer(Xml[Low(XmlString)], Size);
end
{$ELSE}
if (Encoding in [TXmlEncoding.Utf16, TXmlEncoding.Utf16BigEndian]) then
begin
SetLength(Xml, Size div 2);
AStream.ReadBuffer(Xml[Low(XmlString)], Size);
if (Encoding = TXmlEncoding.Utf16BigEndian) then
SwapEndian16(Pointer(Xml), Length(Xml));
end
{$ENDIF}
else
begin
{ We need to convert }
var Bytes: TBytes;
SetLength(Bytes, Size);
AStream.ReadBuffer(Bytes, Size);
case Encoding of
TXmlEncoding.Utf8:
{$IFDEF XML_UTF8}
Assert(False, 'Should be handled elsewhere');
{$ELSE}
Xml := Utf8ToUtf16(@Bytes[0], Size);
{$ENDIF}
TXmlEncoding.Utf16:
{$IFDEF XML_UTF8}
Xml := Utf16ToUtf8(@Bytes[0], Size div 2);
{$ELSE}
Assert(False, 'Should be handled elsewhere');
{$ENDIF}
TXmlEncoding.Utf16BigEndian:
begin
{$IFDEF XML_UTF8}
SwapEndian16(@Bytes[0], Size div 2);
Xml := Utf16ToUtf8(@Bytes[0], Size div 2);
{$ELSE}
Assert(False, 'Should be handled elsewhere');
{$ENDIF}
end;
TXmlEncoding.Utf32:
{$IFDEF XML_UTF8}
Xml := Utf32ToUtf8(@Bytes[0], Size div 4);
{$ELSE}
Xml := Utf32ToUtf16(@Bytes[0], Size div 4);
{$ENDIF}
TXmlEncoding.Utf32BigEndian:
begin
SwapEndian32(@Bytes[0], Size div 4);
{$IFDEF XML_UTF8}
Xml := Utf32ToUtf8(@Bytes[0], Size div 4);
{$ELSE}
Xml := Utf32ToUtf16(@Bytes[0], Size div 4);
{$ENDIF}
end;
else
Assert(False);
end;
end;
Result := TXmlReader.Create(Xml, Encoding, AInternPool, AOptions);
end;
function TXmlReader.Next(out AState: TXmlReaderState): Boolean;
begin
while (True) do
begin
FPrev := FCurrent;
var P := FCurrent;
var Start := P;
{ Scan until '<' }
while (P^ <> #0) and (P^ <> '<') do
Inc(P);
if (P^ = #0) then
begin
AState := TXmlReaderState.EndOfStream;
Exit(False);
end;
if (P <> Start) then
begin
if (SetValue(Start, P)) then
begin
AState := TXmlReaderState.Text;
FCurrent := P;
Exit(True);
end;
end;
Inc(P);
FCurrent := P;
case P^ of
'?': ParseDeclaration; { Ignore and parse next }
'/': begin
ParseEndElement;
AState := TXmlReaderState.EndElement;
Exit(True);
end;
'!': if (P[1] = '[') then
begin
ParseCData;
AState := TXmlReaderState.CData;
Exit(True);
end
else
begin
ParseComment;
AState := TXmlReaderState.Comment;
Exit(True);
end;
else
ParseStartElement;
AState := TXmlReaderState.StartElement;
Exit(True);
end;
end;
end;
procedure TXmlReader.ParseCData;
begin
var P := FCurrent;
if (P[0] <> '!') or (P[1] <> '[') or (P[2] <> 'C') or (P[3] <> 'D')
or (P[4] <> 'A') or (P[5] <> 'T') or (P[6] <> 'A') or (P[7] <> '[')
then
ParseError(@RS_XML_INVALID_CDATA);
Inc(P, 8);
var Start := P;
{ Move to end of CDATA. }
while (P^ <> #0) and ((P[0] <> ']') or (P[1] <> ']') or (P[2] <> '>')) do
Inc(P);
if (P^ = #0) then
ParseError(@RS_XML_UNEXPECTED_EOF);
SetString(FValueString, Start, P - Start);
FCurrent := P + 3;
end;
procedure TXmlReader.ParseComment;
begin
var P := FCurrent;
if (P[0] <> '!') or (P[1] <> '-') or (P[2] <> '-') then
ParseError(@RS_XML_INVALID_COMMENT);
Inc(P, 3);
var Start := P;
var Closed := False;
{ Move to end of comment. }
while not Closed do
begin
if (P^ = #0) then
ParseError(@RS_XML_UNEXPECTED_EOF);
Closed := (P >= (Start + 2)) and (P^ = '>') and (P[-1] = '-') and (P[-2] = '-');
Inc(P);
end;
SetString(FValueString, Start, P - Start - 3);
FCurrent := P;
end;
procedure TXmlReader.ParseDeclaration;
begin
var P := FCurrent;
while (P^ <> #0) and (P^ <> '>') do
Inc(P);
if (P^ = #0) then
ParseError(@RS_XML_UNEXPECTED_EOF);
FCurrent := P + 1;
end;
procedure TXmlReader.ParseEndElement;
begin
FIsEmptyElement := False;
FAttributes.Clear;
var P := FCurrent + 1;
var Start := P;
while (P^ <> #0) and (P^ <> '>') do
Inc(P);
if (P^ = #0) then
ParseError(@RS_XML_UNEXPECTED_EOF);
FValueIndex := FInternPool.Get(Start, P - Start);
FCurrent := P + 1;
end;
procedure TXmlReader.ParseError(const AMsg: PResStringRec);
begin
var Xml := PXmlChar(FXml);
var Position := 0;
if (FCurrent <> nil) then
Position := FPrev - Xml;
raise EXmlParserError.Create(LoadResString(AMsg), Xml, Position);
end;
procedure TXmlReader.ParseStartElement;
begin
var P := FCurrent;
var NameStart := P;
FIsEmptyElement := False;
FAttributes.Clear;
{ Move to first attribute or end of element }
while (P^ > #$20) and (P^ <> '>') do
Inc(P);
var NameEnd := P;
{ Parse attributes }
while (P^ <> '>') do
begin
if (P^ = #0) then
ParseError(@RS_XML_UNEXPECTED_EOF);
if (P^ = '/') then
begin
FIsEmptyElement := True;
Inc(P);
end
else if (P^ <= #$20) then
Inc(P)
else
begin
{ At attribute name }
FPrev := P;
var AttrNameStart := P;
while (P^ > #$20) and (P^ <> '=') do
Inc(P);
if (P^ = #0) then
ParseError(@RS_XML_UNEXPECTED_EOF);
var AttrNameEnd := P;
while (P^ > #0) and (P^ <= #$20) do
Inc(P);
FPrev := P;
if (P^ <> '=') then
ParseError(@RS_XML_EQUAL_EXPECTED);
Inc(P);
FPrev := P;
while (P^ > #0) and (P^ <= #$20) do
Inc(P);
if (P^ = #0) then
ParseError(@RS_XML_UNEXPECTED_EOF);
{ At attribute value }
var QuoteChar := P^;
if (QuoteChar <> '''') and (QuoteChar <> '"') then
ParseError(@RS_XML_INVALID_QUOTE);
Inc(P);
FPrev := P;
var AttrValueStart := P;
while (P^ > #0) and (P^ <> QuoteChar) do
Inc(P);
if (P^ = #0) then
ParseError(@RS_XML_UNEXPECTED_EOF);
AddAttribute(AttrNameStart, AttrNameEnd, AttrValueStart, P);
Inc(P);
end;
end;
if (NameEnd > NameStart) and (NameEnd[-1] = '/') then
begin
FIsEmptyElement := True;
Dec(NameEnd);
end;
FValueIndex := FInternPool.Get(NameStart, NameEnd - NameStart);
FCurrent := P + 1;
end;
function TXmlReader.SetValue(const AStart, AEnd: PXmlChar): Boolean;
var
Buf: TCharBuffer;
begin
Result := False;
Buf.Initialize;
try
var P := AStart;
while (P < AEnd) do
begin
if (P^ = '&') then
begin
FPrev := P;
Inc(P);
var Start := P;
while (P < AEnd) and (P^ <> ';') do
Inc(P);
if (P = AEnd) then
ParseError(@RS_XML_CHARACTER_REFERENCE);
if (Start^ = '#') then
begin
{ Numeric reference }
var S: XmlString;
SetString(S, Start + 1, P - Start - 1);
if (Start[1] = 'x') then
{ Hexadicimal }
S[Low(XmlString)] := '$';
var CodePoint: Cardinal;
if (not TryStrToUInt(S, CodePoint)) then
ParseError(@RS_XML_CHARACTER_REFERENCE);
if (CodePoint < $80) then
Buf.Append(XmlChar(CodePoint))
else
begin
S := XmlString(Char.ConvertFromUtf32(Codepoint));
for var C in S do
Buf.Append(C);
end;
if (not Char.IsWhiteSpace(CodePoint)) then
Result := True;
end
else if (Start^ = 'a') then
begin
{ & or ' }
if (Start[1] = 'm') then
begin
if (Start[2] = 'p') and (Start[3] = ';') then
begin
Buf.Append('&');
Result := True;
end;
end
else if (Start[1] = 'p') then
begin