forked from Avemey/zexmlss
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Excel4Delphi.Xml.pas
3948 lines (3633 loc) · 120 KB
/
Excel4Delphi.Xml.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 Excel4Delphi.Xml;
interface
uses
SysUtils, Classes;
const
BOMUTF8 = #239#187#191; // EF BB BF
BOMUTF16BE = #254#255; // FE FF
BOMUTF16LE = #255#254; // FF FE
BOMUTF32BE = #0#0#254#255; // 00 00 FE FF
BOMUTF32LE = #255#254#0#0; // FF FE 00 00
type
/// <summary>
/// Xml tag type.
/// </summary>
TXmlTagType = (
// Unknown.
xttUnknown = 0,
/// <?...?>
xttDeclare = 1,
/// <![CDATA[..]]>
xttCData = 2,
/// <!--..-->
xttComment = 3,
/// <...>
xttStart = 4,
/// <.../>
xttClosed = 5,
//</...>
xttEnd = 6
);
/// <summary>
/// Text converter from local encoding to needed encoding
/// </summary>
TAnsiToCPConverter = function (const AnsiText: ansistring): AnsiString;
TReadCPCharObj = procedure(var RetChar: ansistring; var _eof: Boolean) of object;
TReadCPChar = procedure(const ReadCPChar: TReadCPCharObj; var text: AnsiString; var _eof: Boolean);
/// <summary>
/// Text converter from reading encoding to local encoding
/// </summary>
TCPToAnsiConverter = TAnsiToCPConverter;
/// <summary>
/// Attribute-value
/// </summary>
TZAttrArray = array [0..1] of AnsiString;
TagsProp = record
Name: AnsiString;
CloseTagNewLine: Boolean;
end;
/// <summary>
/// Builder attributes for tags.
/// </summary>
TZAttributes = class(TPersistent)
private
FCount: integer;
FMaxCount: integer; //реальное кол-во элементов
FItems: array of TZAttrArray;
function GetAttrS(const Att: ansistring): ansistring;
procedure SetAttrS(const Att: ansistring; const Value: ansistring);
function GetAttrI(num: integer): ansistring;
procedure SetAttrI(num: integer; const Value: ansistring);
function GetAttr(num: integer): TZAttrArray;
procedure SetAttr(num: integer; const Value: TZAttrArray);
protected
procedure ResizeItemsArray(NewSize: integer);
public
constructor Create();
destructor Destroy(); override;
procedure Assign(Source: TPersistent); override;
/// <summary>
/// Adds attribute
/// </summary>
/// <param name="AttrName">
/// Attribute Name
/// </param>
/// <param name="TestMatch">
/// Checks for attribute AttrName entry, if attribute was entered then changes it's value, else new attribute is added.
/// </param>
procedure Add(const AttrName: ansistring; const Value: ansistring; TestMatch: boolean = true); overload;
/// <summary>
/// Adds attributes
/// </summary>
/// <param name="Attr">
/// Attributes
/// </param>
/// <param name="TestMatch">
/// Checks for attribute AttrName entry, if attribute was entered then changes it's value, else new attribute is added.
/// </param>
procedure Add(const Attr: TZAttrArray; TestMatch: boolean = true); overload;
/// <summary>
/// Adds attributes
/// </summary>
/// <param name="Att">
/// Attributes
/// </param>
/// <param name="TestMatch">
/// Checks for attribute AttrName entry, if attribute was entered then changes it's value, else new attribute is added.
/// </param>
procedure Add(Att: array of TZAttrArray; TestMatch: boolean = true); overload;
/// <summary>
/// Delete all atributes.
/// </summary>
procedure Clear();
/// <summary>
/// Delete attribute with number Index. Attributes with larger number are shifting left.
/// </summary>
procedure DeleteItem(Index: integer);
/// <summary>
/// Adds attribute AttrName with value Value on position Index.
/// </summary>
procedure Insert(Index: integer; const AttrName: AnsiString; const Value: AnsiString; TestMatch: boolean = true); overload;
/// <summary>
/// Adds attribute AttrName with value Value on position Index.
/// </summary>
procedure Insert(Index: integer; const Attr: TZAttrArray; TestMatch: boolean = true); overload;
/// <summary>
/// Return string with attributes.
/// </summary>
/// <param name="quote">
/// quotation mark for attribute.
/// </param>
/// <param name="CheckEntity">
/// if true then corrects entity
/// </param>
/// <param name="addempty">
/// true then do not add attributes with empty value.
/// </param>
function ToString(quote: ansichar; CheckEntity: boolean; addempty: boolean): ansistring; reintroduce; overload; virtual;
/// <summary>
/// Return string with attributes.
/// </summary>
/// <param name="quote">
/// quotation mark for attribute.
/// </param>
/// <param name="CheckEntity">
/// if true then corrects entity
/// </param>
function ToString(quote: ansichar; CheckEntity: boolean): ansistring; reintroduce; overload; virtual;
/// <summary>
/// Return string with attributes.
/// </summary>
/// <param name="quote">
/// quotation mark for attribute.
/// </param>
function ToString(quote: ansichar): ansistring; reintroduce; overload; virtual;
/// <summary>
/// Return string with attributes.
/// </summary>
/// <param name="CheckEntity">
/// If true then corrects entity
/// </param>
function ToString(CheckEntity: boolean): ansistring; reintroduce; overload; virtual;
/// <summary>
/// Return string with attributes.
/// </summary>
function ToString(): ansistring; reintroduce; overload; virtual;
function IsContainsAttribute(const AttrName: string; CaseSensitivity: boolean = true): boolean;
/// <summary>
/// Number of attributes. (RO)
/// </summary>
property Count: integer read FCount;
/// <summary>
/// Access to the attribute-value by number num.
/// </summary>
property Items[num: integer]: TZAttrArray read GetAttr write SetAttr;
/// <summary>
/// Access to the attribute value by name Att.
/// </summary>
property ItemsByName[const Att: ansistring]: ansistring read GetAttrS write SetAttrS; default;
/// <summary>
/// Access to the attribute value by number num.
/// </summary>
property ItemsByNum[num: integer]: ansistring read GetAttrI write SetAttrI;
end;
/// <summary>
/// Class-writer can write xml to string, stream or file in Windows-1251, UTF-8, UTF-16 (BE and LE) encodings.
/// Use TextConverter property for write in other encodings.
/// </summary>
TZsspXMLWriter = class
private
FAttributeQuote: ansichar; //какие кавычки используем для атрибутов
FAttributes: TZAttributes;
FTags: array of TagsProp; //"Стек тэгов"
FTagCount: integer; //кол-во тэгов в "стеке тэгов"
FMaxTagCount: integer; //Реальный размер FTags
FBuffer: ansistring;
FMaxBufferLength: integer;
FInProcess: boolean;
FStream: TStream;
FTextConverter: TAnsiToCPConverter;
FNewLine: boolean;
FUnixNLSeparator: boolean;
FNLSeparator: ansistring;
FTab: ansistring;
FTabSymbol: ansistring;
FTabLength: integer;
function GetTag(num: integer): ansistring;
function GetTabSymbol(): ansichar;
procedure SetAttributeQuote(Value: ansichar);
procedure SetMaxBufferLength(Value: integer);
procedure SetNewLine(Value: boolean);
procedure SetTabLength(Value: integer);
procedure SetTabSymbol(Value: ansichar);
procedure SetTextConverter(Value: TAnsiToCPConverter);
procedure SetUnixNLSeparator(Value: boolean);
procedure SetAttributes(Value: TZAttributes);
protected
procedure AddText(const Text: ansistring; UseConverter: boolean = true);
procedure AddNode(const TagName: ansistring; CloseTagNewLine: boolean);
function GetTab(num: integer = 0): ansistring;
procedure _AddTag(const _begin: ansistring; text: ansistring; const _end: ansistring; StartNewLine: boolean; _tab: integer = 0);
procedure ResizeTagArray(NewSize: integer);
public
constructor Create(Stream: TStream);
destructor Destroy(); override;
/// <summary>
/// End writing to string/file/stream. Sets InProcess False.
/// </summary>
procedure EndSaveTo();
/// <summary>
/// Empties the Buffer. All characters from Buffer have been written to a file.
/// </summary>
procedure FlushBuffer();
/// <summary>
/// Write CDATA. CDATA - text. CorrectCDATA - if true then replaces ']]>' on ']]&gt;'.
/// StartNewLine - if true then starts from new line (ignored when NewLine = false).
/// </summary>
/// <param name="CDATA">
/// text
/// </param>
/// <param name="CorrectCDATA">
/// if true then replaces ']]>' on ']]&gt;'
/// </param>
/// <param name="StartNewLine">
/// if true then starts from new line (ignored when NewLine = false)
/// </param>
procedure WriteCDATA(CDATA: ansistring; CorrectCDATA: boolean; StartNewLine: boolean = true); overload; //<![CDATA[ bla-bla-bla <><><>...]]>
/// <summary>
/// Write CDATA. CDATA - text. CorrectCDATA - if true then replaces ']]>' on ']]&gt;'.
/// StartNewLine - if true then starts from new line (ignored when NewLine = false).
/// </summary>
/// <param name="CDATA">
/// text
/// </param>
procedure WriteCDATA(const CDATA: ansistring); overload;
/// <summary>
/// Write comment.
/// </summary>
/// <param name="Comment">
/// text of comment.
/// </param>
/// <param name="StartNewLine">
/// if true then start from new line (ignored when NewLine = false).
/// </param>
procedure WriteComment(const Comment: ansistring; StartNewLine: boolean = true);
procedure WriteEmptyTag(const TagName: ansistring; SAttributes: TZAttributes; StartNewLine: boolean; CheckEntity: boolean = true); overload; // <tag a="a"... />
procedure WriteEmptyTag(const TagName: ansistring; AttrArray: array of TZAttrArray; StartNewLine: boolean; CheckEntity: boolean = true); overload;
/// <summary>
/// Write empty tag.
/// </summary>
/// <param name="TagName">
/// name of tag
/// </param>
/// <param name="StartNewLine">
/// if true then start from new line (ignored when NewLine = false).
/// </param>
/// <param name="CheckEntity">
/// if true then corrects entity.
/// </param>
procedure WriteEmptyTag(const TagName: ansistring; StartNewLine: boolean; CheckEntity: boolean = true); overload;
/// <summary>
/// Write empty tag.
/// </summary>
procedure WriteEmptyTag(const TagName: ansistring; SAttributes: TZAttributes); overload;
/// <summary>
/// Write empty tag.
/// </summary>
procedure WriteEmptyTag(const TagName: ansistring; AttrArray: array of TZAttrArray); overload;
/// <summary>
/// Write empty tag.
/// </summary>
/// <param name="TagName">
/// name of tag
/// </param>
procedure WriteEmptyTag(const TagName: ansistring); overload;
/// <summary>
/// Write end of node.
/// </summary>
procedure WriteEndTagNode(); overload;
/// <summary>
/// Write end of node.
/// </summary>
procedure WriteEndTagNode(isForce: boolean; CloseTagNewLine: boolean); overload;
/// <summary>
/// Write instruction
/// </summary>
/// <param name="InstructionName">
/// name of instruction.
/// </param>
/// <param name="SAttributes">
/// attributes
/// </param>
/// <param name="StartNewLine">
/// if true then start from new line (ignored when NewLine = false)
/// </param>
/// <param name="CheckEntity">
/// if true then corrects entity.
/// </param>
procedure WriteInstruction(const InstructionName: ansistring; SAttributes: TZAttributes; StartNewLine: boolean; CheckEntity: boolean = true); overload;
/// <summary>
/// Write instruction
/// </summary>
/// <param name="InstructionName">
/// name of instruction.
/// </param>
/// <param name="SAttributes">
/// attributes
/// </param>
/// <param name="StartNewLine">
/// if true then start from new line (ignored when NewLine = false)
/// </param>
/// <param name="CheckEntity">
/// if true then corrects entity.
/// </param>
procedure WriteInstruction(const InstructionName: ansistring; AttrArray: array of TZAttrArray; StartNewLine: boolean; CheckEntity: boolean = true); overload;
/// <summary>
/// Write instruction
/// </summary>
/// <param name="InstructionName">
/// name of instruction.
/// </param>
/// <param name="StartNewLine">
/// if true then start from new line (ignored when NewLine = false)
/// </param>
/// <param name="CheckEntity">
/// if true then corrects entity.
/// </param>
procedure WriteInstruction(const InstructionName: ansistring; StartNewLine: boolean; CheckEntity: boolean = true); overload;
/// <summary>
/// Write instruction
/// </summary>
/// <param name="InstructionName">
/// name of instruction.
/// </param>
/// <param name="SAttributes">
/// attributes
/// </param>
procedure WriteInstruction(const InstructionName: ansistring; SAttributes: TZAttributes); overload;
/// <summary>
/// Write instruction
/// </summary>
/// <param name="InstructionName">
/// name of instruction.
/// </param>
/// <param name="SAttributes">
/// attributes
/// </param>
procedure WriteInstruction(const InstructionName: ansistring; AttrArray: array of TZAttrArray); overload;
/// <summary>
/// Write instruction
/// </summary>
/// <param name="InstructionName">
/// name of instruction.
/// </param>
procedure WriteInstruction(const InstructionName: ansistring); overload;
/// <summary>
/// <para>
/// Write not processed text. Text
/// </para>
/// <note type="warning">
/// can break XML!
/// </note>
/// </summary>
/// <param name="Text">
/// text
/// </param>
/// <param name="UseConverter">
/// used TextConverter
/// </param>
/// <param name="StartNewLine">
/// if true then start from new line (ignored when NewLine = false).
/// </param>
procedure WriteRaw(Text: ansistring; UseConverter: boolean; StartNewLine: boolean = true);
procedure WriteTag(const TagName: ansistring; const Text: ansistring; SAttributes: TZAttributes; StartNewLine: boolean; CloseTagNewLine: boolean; CheckEntity: boolean = true); overload;
procedure WriteTag(const TagName: ansistring; const Text: ansistring; AttrArray: array of TZAttrArray; StartNewLine: boolean; CloseTagNewLine: boolean; CheckEntity: boolean = true); overload;
/// <summary>
/// Write tag (<tag ...>text</tag>).
/// </summary>
/// <param name="TagName">
/// name of tag
/// </param>
/// <param name="Text">
/// text
/// </param>
/// <param name="StartNewLine">
/// if true then start from new line (ignored when NewLine = false).
/// </param>
/// <param name="CloseTagNewLine">
/// if true then closed tag starts from new line.
/// </param>
/// <param name="CheckEntity">
/// if true then corrects entity.
/// </param>
procedure WriteTag(const TagName: ansistring; const Text: ansistring; StartNewLine: boolean; CloseTagNewLine: boolean; CheckEntity: boolean = true); overload;
/// <summary>
/// Write tag (<tag ...>text</tag>).
/// </summary>
/// <param name="TagName">
/// name of tag
/// </param>
/// <param name="Text">
/// text
/// </param>
/// <param name="SAttributes">
/// Attributes
/// </param>
procedure WriteTag(const TagName: ansistring; const Text: ansistring; SAttributes: TZAttributes); overload;
/// <summary>
/// Write tag (<tag ...>text</tag>).
/// </summary>
/// <param name="TagName">
/// name of tag
/// </param>
/// <param name="Text">
/// text
/// </param>
/// <param name="SAttributes">
/// Attributes
/// </param>
procedure WriteTag(const TagName: ansistring; const Text: ansistring; AttrArray: array of TZAttrArray); overload;
/// <summary>
/// Write tag (<tag ...>text</tag>).
/// </summary>
/// <param name="TagName">
/// name of tag
/// </param>
/// <param name="Text">
/// text
/// </param>
procedure WriteTag(const TagName: ansistring; const Text: ansistring); overload;
/// <summary>
/// Write node.
/// </summary>
/// <param name="TagName">
/// name of tag
/// </param>
/// <param name="SAttributes">
/// Attributes
/// </param>
/// <param name="StartNewLine">
/// if true then start from new line (ignored when NewLine = false).
/// </param>
/// <param name="CloseTagNewLine">
/// if true then closed tag starts from new line.
/// </param>
/// <param name="CheckEntity">
/// if true then corrects entity. Attributes get from Attributes.
/// </param>
procedure WriteTagNode(const TagName: ansistring; SAttributes: TZAttributes; StartNewLine: boolean; CloseTagNewLine: boolean; CheckEntity: boolean = true); overload;
/// <summary>
/// Write node.
/// </summary>
/// <param name="TagName">
/// name of tag
/// </param>
/// <param name="AttrArray">
/// Attributes
/// </param>
/// <param name="StartNewLine">
/// if true then start from new line (ignored when NewLine = false).
/// </param>
/// <param name="CloseTagNewLine">
/// if true then closed tag starts from new line.
/// </param>
/// <param name="CheckEntity">
/// if true then corrects entity. Attributes get from Attributes.
/// </param>
procedure WriteTagNode(const TagName: ansistring; AttrArray: array of TZAttrArray; StartNewLine: boolean; CloseTagNewLine: boolean; CheckEntity: boolean = true); overload;
/// <summary>
/// Write node.
/// </summary>
/// <param name="TagName">
/// name of tag
/// </param>
/// <param name="StartNewLine">
/// if true then start from new line (ignored when NewLine = false).
/// </param>
/// <param name="CloseTagNewLine">
/// if true then closed tag starts from new line.
/// </param>
/// <param name="CheckEntity">
/// if true then corrects entity.
/// </param>
procedure WriteTagNode(const TagName: ansistring; StartNewLine: boolean; CloseTagNewLine: boolean; CheckEntity: boolean = true); overload;
/// <summary>
/// Write node.
/// </summary>
/// <param name="TagName">
/// name of tag
/// </param>
/// <param name="SAttributes">
/// Attributes
/// </param>
procedure WriteTagNode(const TagName: ansistring; SAttributes: TZAttributes); overload;
/// <summary>
/// Write node.
/// </summary>
/// <param name="TagName">
/// name of tag
/// </param>
/// <param name="AttrArray">
/// Attributes
/// </param>
procedure WriteTagNode(const TagName: ansistring; AttrArray: array of TZAttrArray); overload;
/// <summary>
/// Write node.
/// </summary>
/// <param name="TagName">
/// name of tag
/// </param>
procedure WriteTagNode(const TagName: ansistring); overload;
/// <summary>
/// Tag's attributes.
/// </summary>
property Attributes: TZAttributes read FAttributes write SetAttributes;
/// <summary>
/// Quotation mark for attribute values ( ' (prime) or " (double prime)). <br />" (double prime) by default.
/// </summary>
property AttributeQuote: ansichar read FAttributeQuote write SetAttributeQuote;
/// <summary>
/// Buffer. (read only)
/// </summary>
property Buffer: AnsiString read FBuffer;
/// <summary>
/// Return True if writing in process. (read only)
/// </summary>
property InProcess: boolean read FInProcess;
/// <summary>
/// Buffer length (>0). If InProcess = True then property read only. <br />4096 bytes by default.
/// </summary>
property MaxBufferLength: integer read FMaxBufferLength write SetMaxBufferLength;
/// <summary>
/// If True then tag starts with new line. If InProcess = True then property read only. <br />True by default
/// </summary>
property NewLine: boolean read FNewLine write SetNewLine;
/// <summary>
/// Number of tab-symbols before tag. If InProcess = True then property read only. <br />0 by default.
/// </summary>
property TabLength: integer read FTabLength write SetTabLength;
/// <summary>
/// Tab symbol (#32 (space) or #9 (tab)). If InProcess = True then property read only. <br />#32 by default.
/// </summary>
property TabSymbol: ansichar read GetTabSymbol write SetTabSymbol;
/// <summary>
/// Number of open tags before current tag. (read only)
/// </summary>
property TagCount: integer read FTagCount;
/// <summary>
/// Return open tag number num. (read only)
/// </summary>
property Tags[num: integer]: ansistring read GetTag;
/// <summary>
/// Set text converter. If InProcess = True then property read only.
/// </summary>
Property TextConverter: TAnsiToCPConverter read FTextConverter write SetTextConverter;
/// <summary>
/// If True then newline character is #10 (LF) else newline "character" is #13#10 (CR+LF).
/// </summary>
property UnixNLSeparator: boolean read FUnixNLSeparator write SetUnixNLSeparator;
end;
/// <summary>
/// Class-reader. Read XML from string, stream or file in CP866, Windows-1251, UTF-8 and UTF-16 (BE and LE) encodings.
/// </summary>
TZsspXMLReader = class
private
FAttributes: TZAttributes; //Атрибуты
FStream: TStream;
FTags: array of ansistring; //"Стек тэгов"
FTagCount: integer; //кол-во тэгов в "стеке тэгов"
FMaxTagCount: integer; //Реальный размер FTags
FBuffer: ansistring; //буфер
FMaxBufferLength: integer; //Размер буфера
FInProcess: boolean; //в процессе чтения
FSourceType: byte; //1 - файл, 2 - поток, 3 - строка
FPFirst: integer; //Начало буфера
FPLast: integer; //Конец буфера
FTextBeforeTag: ansistring; //Текст до тэга
FErrorCode: integer; //код ошибки (0 - всё нормально)
// and 1 = 1 - значение параметра без кавычек (<TAG param=value>)
// and 2 = 2 - <TAG ... param = > или <TAG ... param = = ...> (значение параметра без кавычек)
// and 4 = 4 - <TAG ... param = value = ...> (значение параметра без кавычек)
// and 8 = 8 - <TAG ... param =/...> (значение параметра без кавычек)
// and 16 = 16 - <TAG ... param = value"...> (нет открывающей кавычки)
// and 32 = 32 - <TAG ... param = <*va<*lue<*... > <TAG ... param = <*"value"... > (* - 0 или более)
// and 64 = 64 - <TAG ... param = value/ ... >
// and 128 = 128 - <!Unknown... > Странный комментарий
// and 256 = 256 - <=...>
// and 512 = 512 - <tag!*...> - символ '!' в неправильном месте
// and 1024 = 1024 - <tag ... param = ?...>
// and 2048 = 2048 - < tag ... > пробельный символ после <
// and 4096 = 4096 - < tag ... param param ... > ('=' отсутствует)
// and 8192 = 8192 - </|?tag ... /> ('/' или '?')
// and 16384 = 16384 - <tag ... ?>
// and 32768 = 32768 - '<' в неподходящем месте
// and 65536 = 65536 - "'" или '"' в неподходящем месте
// and 131072 = 131072 - неожиданный конец тега
// and 262144 = 262144 - перед закрывающим тэгом нету открывающего
// and 524288 = 524288 - EOF и кол-во тэгов > 0
FRawTextTag: ansistring; //Текст тэга
FTagName: ansistring; //Имя тэга (инструкции/комментария)
FValue: ansistring; //Текст CDATA или комментария
FTagType: TXmlTagType;
FCharReader: TReadCPChar; //Читает "символ"
FCharConverter: TCPToAnsiConverter; //конвертер
FStreamEnd: boolean;
FIgnoreCase: boolean;
FQuotesEqual: boolean;
FAttributesMatch: boolean;
function GetTag(num: integer): ansistring;
procedure SetMaxBufferLength(Value: integer);
procedure SetAttributes(Value: TZAttributes);
procedure AddTag(const Value: ansistring);
procedure DeleteClosedTag();
procedure DeleteTag();
procedure SetIgnoreCase(Value: boolean);
procedure SetQuotesEqual(Value: boolean);
procedure SetAttributesMatch(Value: boolean);
protected
procedure Clear();
procedure ClearAll();
procedure RecognizeEncoding(var txt: ansistring); //Попытка распознания кодировки
procedure ReadBuffer();
procedure GetOneChar(var OneChar: ansistring; var err: boolean);
procedure ResizeTagArray(NewSize: integer);
public
constructor Create(); virtual;
destructor Destroy(); override;
/// <summary>
/// Begin to read XML from Stream.
/// </summary>
/// <returns>
/// 0 if no errors.
/// </returns>
function BeginReadStream(Stream: TStream): integer;
/// <summary>
/// Read tag.
/// </summary>
function ReadTag(): boolean;
/// <summary>
/// End reading.
/// </summary>
procedure EndRead();
/// <returns>
/// True when current file (stream or string) position is the end.
/// </returns>
function Eof(): boolean; virtual;
/// <summary>
/// Attributes of tag.
/// </summary>
property Attributes: TZAttributes read FAttributes write SetAttributes;
property AttributesMatch: boolean read FAttributesMatch write SetAttributesMatch;
/// <summary>
/// Return True when processed XML. (RO)
/// </summary>
property InProcess: boolean read FInProcess;
/// <summary>
/// Raw text. (RO)
/// </summary>
property RawTextTag: ansistring read FRawTextTag;
/// <summary>
/// Return error code. 0 - OK, 1 - value without quotes, etc. (RO)
/// </summary>
property ErrorCode: integer read FErrorCode;
/// <summary>
/// If True then ignore case sensitive. If InProcess = True then property read only. <br />False by default.
/// </summary>
property IgnoreCase: boolean read FIgnoreCase write SetIgnoreCase;
/// <summary>
/// Return name of readed tag/instruction/comment. (RO)
/// </summary>
property TagName: ansistring read FTagName;
/// <summary>
/// Return CDATA or comment text. (RO)
/// </summary>
property TagValue: ansistring read FValue;
/// <summary>
/// Return type of tag.
/// </summary>
property TagType: TXmlTagType read FTagType;
/// <summary>
/// Number of opened tags before current tag. (RO)
/// </summary>
property TagCount: integer read FTagCount;
/// <summary>
/// Return opened tag number num. (RO)
/// </summary>
property Tags[num: integer]: ansistring read GetTag;
property TextBeforeTag: ansistring read FTextBeforeTag;
/// <summary>
/// Buffer size (>=512). If InProcess = True then property read only. <br />4096 bytes by default.
/// </summary>
property MaxBufferLength: integer read FMaxBufferLength write SetMaxBufferLength;
property QuotesEqual: boolean read FQuotesEqual write SetQuotesEqual; //признак того, что двойные и одинарные кавычки
//равны. Если установлено в false, то в <tagname attr1="asda' attr2='adsas">
//будет один атрибут "attr1" cо значением "asda' attr2='adsas",
//в противном случае распознается 2 атрибута: "attr1"="asda" и "attr2"="adsas".
//По умолчанию false.
end;
TZAttrArrayH = array [0..1] of string;
//Класс-обёртка-костыль для атрибутов над TZAttributes
TZAttributesH = class(TPersistent)
private
FAttributes: TZAttributes;
function GetAttrCount(): integer;
function GetAttrS(Att: string): string;
procedure SetAttrS(Att: string; const Value: string);
function GetAttrI(num: integer): string;
procedure SetAttrI(num: integer; const Value: string);
function GetAttr(num: integer): TZAttrArrayH;
procedure SetAttr(num: integer; const Value: TZAttrArrayH);
public
constructor Create();
destructor Destroy(); override;
procedure Add(const AttrName: string; const Value: string; TestMatch: boolean = true); overload;
procedure Add(const Attr: TZAttrArrayH; TestMatch: boolean = true); overload;
procedure Add(Att: array of TZAttrArrayH; TestMatch: boolean = true ); overload;
procedure Assign(Source: TPersistent); override;
procedure Clear();
procedure DeleteItem(Index: integer);
procedure Insert(Index: integer; const AttrName: string; const Value: string; TestMatch: boolean = true); overload;
procedure Insert(Index: integer; const Attr: TZAttrArrayH; TestMatch: boolean = true); overload;
function ToString(quote: char; CheckEntity: boolean; addempty: boolean): string; reintroduce; overload; virtual;
function ToString(quote: char; CheckEntity: boolean): string; reintroduce; overload; virtual;
function ToString(quote: char): string; reintroduce; overload; virtual;
function ToString(CheckEntity: boolean): string; reintroduce; overload; virtual;
function ToString(): string; overload; override;
function IsContainsAttribute(const AttrName: string; CaseSensitivity: boolean = true): boolean;
property Count: integer read GetAttrCount;
property Items[num: integer]: TZAttrArrayH read GetAttr write SetAttr;
property ItemsByName[Att: string]: string read GetAttrS write SetAttrS; default;
property ItemsByNum[num: integer]: string read GetAttrI write SetAttrI;
end;
//пишет XML
TZsspXMLWriterH = class
private
FAttributes: TZAttributesH;
FXMLWriter: TZsspXMLWriter;
function GetXMLBuffer(): string;
function GetAttributeQuote(): char;
function GetInProcess(): boolean;
function GetMaxBufferLength(): integer;
function GetNewLine(): boolean;
function GetTabLength(): integer;
function GetTagCount(): integer;
function GetTextConverter(): TCPToAnsiConverter;
function GetUnixNLSeparator(): boolean;
function GetTag(num: integer): string;
function GetTabSymbol(): char;
procedure SetAttributeQuote(Value: char);
procedure SetMaxBufferLength(Value: integer);
procedure SetNewLine(Value: boolean);
procedure SetTabLength(Value: integer);
procedure SetTabSymbol(Value: char);
procedure SetTextConverter(Value: TAnsiToCPConverter);
procedure SetUnixNLSeparator(Value: boolean);
procedure SetAttributes(Value: TZAttributesH);
protected
public
constructor Create(Stream: TStream);
destructor Destroy(); override;
procedure EndSaveTo();
procedure FlushBuffer();
procedure WriteCDATA(CDATA: string; CorrectCDATA: boolean; StartNewLine: boolean = true); overload; //<![CDATA[ bla-bla-bla <><><>...]]>
procedure WriteCDATA(CDATA: string); overload;
procedure WriteComment(Comment: string; StartNewLine: boolean = true); //<!-- bla-bla-bla -->
procedure WriteEmptyTag(TagName: string; SAttributes: TZAttributesH; StartNewLine: boolean; CheckEntity: boolean = true); overload; // <tag a="a"... />
procedure WriteEmptyTag(TagName: string; AttrArray: array of TZAttrArrayH; StartNewLine: boolean; CheckEntity: boolean = true); overload;
procedure WriteEmptyTag(TagName: string; StartNewLine: boolean; CheckEntity: boolean = true); overload;
procedure WriteEmptyTag(TagName: string; SAttributes: TZAttributesH); overload;
procedure WriteEmptyTag(TagName: string; AttrArray: array of TZAttrArrayH); overload;
procedure WriteEmptyTag(TagName: string); overload;
procedure WriteEndTagNode(); overload;
procedure WriteEndTagNode(isForce: boolean; CloseTagNewLine: boolean); overload;
procedure WriteInstruction(InstructionName: string; SAttributes: TZAttributesH; StartNewLine: boolean; CheckEntity: boolean = true); overload;
procedure WriteInstruction(InstructionName: string; AttrArray: array of TZAttrArrayH; StartNewLine: boolean; CheckEntity: boolean = true); overload;
procedure WriteInstruction(InstructionName: string; StartNewLine: boolean; CheckEntity: boolean = true); overload;
procedure WriteInstruction(InstructionName: string; SAttributes: TZAttributesH); overload;
procedure WriteInstruction(InstructionName: string; AttrArray: array of TZAttrArrayH); overload;
procedure WriteInstruction(InstructionName: string); overload;
procedure WriteRaw(Text: string; UseConverter: boolean; StartNewLine: boolean = true); overload;
procedure WriteRaw(Text: ansistring; UseConverter: boolean; StartNewLine: boolean = true); overload;
procedure WriteTag(TagName: string; Text: string; SAttributes: TZAttributesH; StartNewLine: boolean; CloseTagNewLine: boolean; CheckEntity: boolean = true); overload;
procedure WriteTag(TagName: string; Text: string; AttrArray: array of TZAttrArrayH; StartNewLine: boolean; CloseTagNewLine: boolean; CheckEntity: boolean = true); overload;
procedure WriteTag(TagName: string; Text: string; StartNewLine: boolean; CloseTagNewLine: boolean; CheckEntity: boolean = true); overload;
procedure WriteTag(TagName: string; Text: string; SAttributes: TZAttributesH); overload;
procedure WriteTag(TagName: string; Text: string; AttrArray: array of TZAttrArrayH); overload;
procedure WriteTag(TagName: string; Text: string); overload;
procedure WriteTagNode(TagName: string; SAttributes: TZAttributesH; StartNewLine: boolean; CloseTagNewLine: boolean; CheckEntity: boolean = true); overload;
procedure WriteTagNode(TagName: string; AttrArray: array of TZAttrArrayH; StartNewLine: boolean; CloseTagNewLine: boolean; CheckEntity: boolean = true); overload;
procedure WriteTagNode(TagName: string; StartNewLine: boolean; CloseTagNewLine: boolean; CheckEntity: boolean = true); overload;
procedure WriteTagNode(TagName: string; SAttributes: TZAttributesH); overload;
procedure WriteTagNode(TagName: string; AttrArray: array of TZAttrArrayH); overload;
procedure WriteTagNode(TagName: string); overload;
procedure WriteHeader(CodePageName: string = 'UTF-8'; BOM: AnsiString = '');
property Attributes: TZAttributesH read FAttributes write SetAttributes;
property AttributeQuote: char read GetAttributeQuote write SetAttributeQuote;
property Buffer: string read GetXMLBuffer;
property InProcess: boolean read GetInProcess;
property MaxBufferLength: integer read GetMaxBufferLength write SetMaxBufferLength;
property NewLine: boolean read GetNewLine write SetNewLine;
property TabLength: integer read GetTabLength write SetTabLength;
property TabSymbol: char read GetTabSymbol write SetTabSymbol;
property TagCount: integer read GetTagCount;
property Tags[num: integer]: string read GetTag;
Property TextConverter: TAnsiToCPConverter read GetTextConverter write SetTextConverter;
property UnixNLSeparator: boolean read GetUnixNLSeparator write SetUnixNLSeparator;
end;
//читает XML
TZsspXMLReaderH = class
private
FAttributes: TZAttributesH; //Атрибуты
FXMLReader: TZsspXMLReader;
function GetAttributes(): TZAttributesH;
function GetInProcess(): boolean;
function GetRawTextTag(): string;
function GetErrorCode(): integer;
function GetIgnoreCase(): boolean;
function GetValue(): string;
function GetTagType(): TXmlTagType;
function GetIsTagStart(): boolean;
function GetIsTagClosed(): boolean;
function GetIsTagEnd(): boolean;
function GetTagCount(): integer;
function GetTextBeforeTag(): string;
function GetTagName(): string;
function GetTag(num: integer): string;
procedure SetMaxBufferLength(Value: integer);
function GetMaxBufferLength(): integer;
procedure SetAttributes(Value: TZAttributesH);
procedure SetIgnoreCase(Value: boolean);
procedure SetQuotesEqual(Value: boolean);
function GetQuotesEqual(): boolean;
procedure SetAttributesMatch(Value: boolean);
function GetAttributesMatch(): boolean;
function GetIsTagStartOrClosed: boolean;
function GetIsTagOfData: boolean;
protected
public
constructor Create(); virtual;
destructor Destroy(); override;
function BeginReadStream(Stream: TStream): integer;
function ReadTag(): boolean;
procedure EndRead();
function Eof(): boolean; virtual;
property Attributes: TZAttributesH read GetAttributes write SetAttributes;
property AttributesMatch: boolean read GetAttributesMatch write SetAttributesMatch;
property InProcess: boolean read GetInProcess;
property RawTextTag: string read GetRawTextTag;
property ErrorCode: integer read GetErrorCode;
property IgnoreCase: boolean read GetIgnoreCase write SetIgnoreCase;
property TagName: string read GetTagName;
property TagValue: string read GetValue;
property TagType: TXmlTagType read GetTagType;
property IsTagStart: boolean read GetIsTagStart;
property IsTagClosed: boolean read GetIsTagClosed;
property IsTagStartOrClosed: boolean read GetIsTagStartOrClosed;
property IsTagOfData: boolean read GetIsTagOfData;
property IsTagEnd: boolean read GetIsTagEnd;
property TagCount: integer read GetTagCount;
property Tags[num: integer]: string read GetTag;
property TextBeforeTag: string read GetTextBeforeTag;
property MaxBufferLength: integer read GetMaxBufferLength write SetMaxBufferLength;
property QuotesEqual: boolean read GetQuotesEqual write SetQuotesEqual;
function IsTagEndByName(tagName: string): boolean;
function IsTagStartByName(tagName: string): boolean;
function IsTagClosedByName(tagName: string): boolean;
function IsTagStartOrClosedByName(tagName: string): boolean;
function ReadToEndTagByName(tagName: string): boolean;
function AttribBool(name: string; default: boolean = false): boolean;
function AttribInt(name: string; default: integer = 0): integer;
function AttribDouble(name: string; default: double = 0): double;
function AttribString(name: string): string;
function AsBool(default: boolean = false): boolean;
function AsInt(default: integer = 0): integer;
function AsDouble(default: double = 0): double;
end;
//конец для Delphi >=2009
//Читатали
procedure ReadCharUTF8(const ReadCPChar: TReadCPCharObj; var text: ansistring; var _eof: boolean);
procedure ReadCharUTF16LE(const ReadCPChar: TReadCPCharObj; var text: ansistring; var _eof: boolean);
procedure ReadCharUTF16BE(const ReadCPChar: TReadCPCharObj; var text: ansistring; var _eof: boolean);
procedure ReadCharUTF32(const ReadCPChar: TReadCPCharObj; var text: ansistring; var _eof: boolean);
procedure ReadCharOneByte(const ReadCPChar: TReadCPCharObj; var text: ansistring; var _eof: boolean);
//////////// Конвертеры
function conv_UTF8ToLocal(const Text: ansistring): ansistring;
function conv_UTF16LEToLocal(const Text: ansistring): ansistring;
function conv_UTF16BEToLocal(const Text: ansistring): ansistring;
function conv_UTF32LEToLocal(const Text: ansistring): ansistring;
function conv_UTF32BEToLocal(const Text: ansistring): ansistring;
function conv_WIN1251ToLocal(const Text: ansistring): ansistring;
function conv_CP866ToLocal(const Text: ansistring): ansistring;
//заменяет в строке спецсимволы
function CheckStrEntity(const st: ansistring; checkamp: boolean = true): ansistring; overload;
function CheckStrEntity(const st: string; checkamp: boolean = true): string; overload;
function ClenuapXmlTagValue(const str: string): string;
//проверяем на корректность сущность (не факт, что валидную), в случае
//чего заменяем '&' на '&'
procedure Correct_Entity(const _St: ansistring; num: integer; var _result: ansistring); overload;
procedure Correct_Entity(const _St: string; num: integer; var _result: string); overload;
//Добавляет аттрибут
function ToAttribute(const AttrName: ansistring; const Value: ansistring): TZAttrArray; overload;
function ToAttribute(const AttrName: string; const Value: string): TZAttrArrayH; overload;
//Распознаёт кодировку XML и HTML текста
function RecognizeEncodingXML(startpos: integer; var txt: ansistring; out cpfromtext: integer; out cpname: ansistring; out ftype: integer): boolean; overload;
//Распознаёт BOM (Byte Order Mark) текста
function RecognizeBOM(var txt: ansistring): integer;
//Распознаёт кодировку XML и HTML текста вместе с BOM
function RecognizeEncodingXML(var txt: ansistring; out BOM: integer; out cpfromtext: integer; out cpname: ansistring; out ftype: integer): boolean; overload;
implementation
uses Excel4Delphi.Common;
//// читатели
function DUAnsiPos(const Substr: ansistring; const S: ansistring): integer;
var
i, j: integer;
kol_str: integer;
kol_sub: integer;
b: boolean;
begin
kol_str := Length(s);
kol_sub := Length(substr);
result := 0;
if (kol_sub = 0) then
exit;
for i := 1 to kol_str - kol_sub + 1 do
if (s[i] = Substr[1]) then
begin
b := true;
for j := 2 to kol_sub do
if (s[i + j - 1] <> Substr[j]) then
begin
b := false;
break;
end;
if (b) then
begin
result := i;
break;
end;
end;
end;
procedure ReadCharUTF8(const ReadCPChar: TReadCPCharObj; var text: ansistring; var _eof: boolean);
var
s: ansistring;
t, i: integer;
kol: integer;
begin
_eof := false;
text := '';
s := '';
if Assigned(ReadCPChar) then
begin
ReadCPChar(s, _eof);
text := text + s;
if _eof then exit;
if length(s) > 0 then
begin
t := ord(s[1]);
if t > 127 then
begin
{
//вроде как возможны 5-ти байтные, но в стандарте нету