Check-in [f4fdab492d]

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Added auto-updater unit (and all necessary dependencies: HTTP client, NativeXML parser and helper, version info access).
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: f4fdab492d854fbe5fa9185971c188ab6af98d6e
User & Date: MCO 2014-10-09 19:38:27
Context
2014-10-10
15:42
Use TryStrToInt instead of raising an exception. check-in: 5cfb19ef2b user: tinus tags: trunk
2014-10-09
19:38
Added auto-updater unit (and all necessary dependencies: HTTP client, NativeXML parser and helper, version info access). check-in: f4fdab492d user: MCO tags: trunk
2014-10-08
19:36
Fixed links to downloads. check-in: 1e293a5af5 user: tinus tags: trunk
Changes

Changes to src/F_Main.pas.

33
34
35
36
37
38
39
40

41
42
43
44
45
46
47

var
  frmMain: TfrmMain;
  Settings: TIniFile;

implementation
uses
  ScreenSaverUtils;


{$R *.dfm}

{ ------------------------------------------------------------------------------------------------ }
procedure TfrmMain.FormCreate(Sender: TObject);
var
  i: Integer;







|
>







33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

var
  frmMain: TfrmMain;
  Settings: TIniFile;

implementation
uses
  ScreenSaverUtils,
  U_AutoUpdate;

{$R *.dfm}

{ ------------------------------------------------------------------------------------------------ }
procedure TfrmMain.FormCreate(Sender: TObject);
var
  i: Integer;

Added src/L_HttpClient.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
unit L_HttpClient;

interface
{$WARN SYMBOL_PLATFORM OFF}

uses
  SysUtils, Classes, WinInet;

type
  THttpConnectEnum = (
    hcDirect          = INTERNET_OPEN_TYPE_DIRECT,
    hcPreconfig       = INTERNET_OPEN_TYPE_PRECONFIG,
    hcPreconfigNoAuto = INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY,
    hcProxy           = INTERNET_OPEN_TYPE_PROXY
  );

  THttpClient = class;
  TProgressNotify = procedure(Sender: THttpClient; Msg: string; BytesRead, TotalBytes: Cardinal; out Cancel: Boolean) of object;

  THttpClient = class
    private
      FhReq: HINTERNET;
      FOnProgress: TProgressNotify;
      FURL: string;

      function  SendRequestAndGetResponse(const Verb, Resource: string;
                                          const Data: Pointer; const DataSize: Cardinal;
                                          Flags: Cardinal = 0): integer;
      procedure ReadResponseHeaders;
    protected
      FPath: string;
      FRequestHeaders: TStringList;
      FResponseStatus: cardinal;
      FResponseStatusText: string;
      FResponseHeaders: TStringList;
      FResponseStream: TMemoryStream;

      function QueryInfoString(const InfoFlag: cardinal): string; overload; inline;
      function QueryInfoString(const InfoFlag: cardinal; out Value: string): boolean; overload;
      function QueryInfoInteger(const InfoFlag: cardinal): cardinal; overload; inline;
      function QueryInfoInteger(const InfoFlag: cardinal; out Value: cardinal): Boolean; overload; inline;

      function GetResponseString: string; // RawString
    public
      UserAgent: string;
      Hostname: string;
      Port: integer;
      UseProxy: THttpConnectEnum;
      Proxy, ProxyByPass: string;
      UserName: string;
      Password: string;
      ConnectTimeout, SendTimeout, ReceiveTimeout: Cardinal;

      constructor Create(const URL: string); overload;
      constructor Create(const Hostname, Path: string; const Port: integer = INTERNET_DEFAULT_HTTP_PORT); overload;
      destructor  Destroy; override;

      function Head(Path: string = ''; const BypassCache: Boolean = False): integer;
      function Get(Path: string = ''; const BypassCache: Boolean = False): integer;
      function Post(Data: string): integer; overload;
      function Post(Data: TStream): integer; overload;
      function Post(Path: string; Data: string): integer; overload;
      function Post(Path: string; Data: TStream): integer; overload;

      property Path: string                   read FPath;
      property RequestHeaders: TStringList    read FRequestHeaders;
      property StatusCode: cardinal           read FResponseStatus;
      property StatusText: string             read FResponseStatusText;
      property ResponseHeaders: TStringList   read FResponseHeaders;
      property ResponseStream: TMemoryStream  read FResponseStream;
      property ResponseString: string         read GetResponseString; // RawString
      property URL: string                    read FURL;

      property OnProgress: TProgressNotify    read FOnProgress  write FOnProgress;
  end;

type
  EHttpError = class(Exception);


implementation
uses
  Windows, Math;

const
  READBUFFERSIZE = 4096;
  ERROR_INSUFFICIENT_BUFFER = 122;   { dderror }

resourcestring
  scConnecting =  'Connecting';
  scUploading  =  'Sending';
  scDownloading = 'Receiving';
  scFinished    = 'Done';

{ ================================================================================================ }
{ THttpClient }

{ ------------------------------------------------------------------------------------------------ }
constructor THttpClient.Create(const URL: string);
var
  UC: URL_COMPONENTS;
begin
  UC.dwStructSize := sizeof(UC);
  UC.lpszScheme := nil;
  UC.dwSchemeLength := 0;
  UC.nScheme := INTERNET_SCHEME_UNKNOWN;
  UC.lpszHostName := PChar(StringOfChar(#0, Length(URL) + 1));
  UC.dwHostNameLength := Length(URL) + 1;
  UC.nPort := INTERNET_INVALID_PORT_NUMBER;
  UC.lpszUserName := PChar(StringOfChar(#0, Length(URL) + 1));
  UC.dwUserNameLength := Length(URL) + 1;
  UC.lpszPassword := PChar(StringOfChar(#0, Length(URL) + 1));
  UC.dwPasswordLength := Length(URL) + 1;
  UC.lpszUrlPath := PChar(StringOfChar(#0, Length(URL) + 1));
  UC.dwUrlPathLength := Length(URL) + 1;
  UC.lpszExtraInfo := nil;
  UC.dwExtraInfoLength := 0;

  Win32Check(InternetCrackUrl(PChar(URL), 0, 0, UC));
  if not UC.nScheme in [INTERNET_SCHEME_HTTP, INTERNET_SCHEME_HTTPS, INTERNET_SCHEME_FILE] then begin
    raise EHttpError.CreateFmt('Unsupported scheme used in URL "%s". Only http:// and https:// are supported', [URL]);
  end;
  Create(UC.lpszHostName, UC.lpszUrlPath, UC.nPort);
  Self.UserName := UC.lpszUserName;
  Self.Password := UC.lpszPassword;
end {THttpClient.Create};
{ ------------------------------------------------------------------------------------------------ }
constructor THttpClient.Create(const Hostname, Path: string; const Port: integer);
var
  UC: URL_COMPONENTS;
  Buffer: string;
  Size: Cardinal;
begin
  FPath := Path;
  Self.UserAgent := ChangeFileExt(ExtractFileName(ParamStr(0)), '');
  Self.Hostname := Hostname;
  Self.Port := Port;
  Self.UseProxy := hcPreconfig;
  FRequestHeaders := TStringList.Create;
  FRequestHeaders.NameValueSeparator := ':';
  ConnectTimeout := 0;
  SendTimeout := 0;
  ReceiveTimeout := 0;

  Size := INTERNET_MAX_URL_LENGTH;
  SetLength(Buffer, Size);
  if InternetCreateUrl(UC, ICU_ESCAPE, PChar(Buffer), Size) then begin
    FURL := Copy(Buffer, 1, Size);
  end else if GetLastError = ERROR_INSUFFICIENT_BUFFER then begin
    SetLength(Buffer, Size);
    if InternetCreateUrl(UC, ICU_ESCAPE, PChar(Buffer), Size) then begin
      FURL := Copy(Buffer, 1, Size);
    end;
  end;
end {THttpClient.Create};
{ ------------------------------------------------------------------------------------------------ }
destructor THttpClient.Destroy;
begin
  if Assigned(FResponseStream) then FreeAndNil(FResponseStream);
  if Assigned(FResponseHeaders) then FreeAndNil(FResponseHeaders);
  FRequestHeaders.Free;
  inherited;
end {THttpClient.Destroy};

{ ------------------------------------------------------------------------------------------------ }
function THttpClient.Head(Path: string = ''; const BypassCache: Boolean = False): integer;
begin
  if Path = '' then begin
    Path := FPath;
  end;
  if BypassCache then begin
    Result := SendRequestAndGetResponse('HEAD', Path, nil, 0, INTERNET_FLAG_RELOAD);
  end else begin
    Result := SendRequestAndGetResponse('HEAD', Path, nil, 0);
  end;
end {THttpClient.Head};

{ ------------------------------------------------------------------------------------------------ }
function THttpClient.Get(Path: string = ''; const BypassCache: Boolean = False): integer;
begin
  if Path = '' then begin
    Path := FPath;
  end;
  if BypassCache then begin
    Result := SendRequestAndGetResponse('GET', Path, nil, 0, INTERNET_FLAG_RELOAD);
  end else begin
    Result := SendRequestAndGetResponse('GET', Path, nil, 0);
  end;
end {THttpClient.Get};

{ ------------------------------------------------------------------------------------------------ }
function THttpClient.Post(Data: TStream): integer;
begin
  Result := Self.Post(FPath, Data);
end {THttpClient.Post};
{ ------------------------------------------------------------------------------------------------ }
function THttpClient.Post(Path: string; Data: TStream): integer;
var
  MemData: TMemoryStream;
  CleanUp: boolean;
begin
  if Data is TMemoryStream then begin
    MemData := TMemoryStream(Data);
    CleanUp := False;
  end else begin
    Data.Position := 0;
    MemData := TMemoryStream.Create;
    MemData.CopyFrom(Data, Data.Size);
    CleanUp := True;
  end;
  try
    Result := SendRequestAndGetResponse('POST', Path, MemData.Memory, MemData.Size);
  finally
    if CleanUp then begin
      MemData.Free;
    end;
  end;
end {THttpClient.Post};
{ ------------------------------------------------------------------------------------------------ }
function THttpClient.Post(Data: string): integer;
begin
  Result := Self.Post(FPath, Data);
end {THttpClient.Post};
{ ------------------------------------------------------------------------------------------------ }
function THttpClient.Post(Path: string; Data: string): integer;
begin
  Result := SendRequestAndGetResponse('POST', Path, PChar(Data), ByteLength(Data));
end {THttpClient.Post};

{ ------------------------------------------------------------------------------------------------ }
function THttpClient.SendRequestAndGetResponse(const Verb, Resource: string;
                                               const Data: Pointer;
                                               const DataSize: Cardinal;
                                               Flags: Cardinal = 0): integer;
var
  hInt, hConn: HINTERNET;
  PProxy, PProxyBypass, PUserName, PPassword: PChar;
  BytesRead, TotalBytesToRead, TotalBytesRead: Cardinal;
  Buffer: TMemoryStream;
  Size: Cardinal;
  Cancel: Boolean;
begin
  Result := 0; // means the request has been canceled

  FPath := Resource;

  { Initialize the response data }
  FResponseStatus := 0;
  FResponseStatusText := '';
  if Assigned(FResponseHeaders) then FreeAndNil(FResponseHeaders);
  if Assigned(FResponseStream) then FreeAndNil(FResponseStream);

  { Set the proxy parameters }
  if UseProxy = hcProxy then begin
    if Length(Self.Proxy) = 0 then begin
      PProxy := nil;
    end else begin
      PProxy := PChar(Self.Proxy);
    end;
    if Length(Self.ProxyByPass) = 0 then begin
      PProxyByPass := nil;
    end else begin
      PProxyByPass := PChar(Self.ProxyByPass);
    end;
  end else begin
    PProxy := nil;
    PProxyBypass := nil;
  end;

  Cancel := False;
  if Assigned(FOnProgress) then begin
    FOnProgress(Self, scConnecting, 0, 0, Cancel);
    if Cancel then
      Exit;
  end;

  { Open an internet handle and set the request parameters }
  hInt := InternetOpen(PChar(UserAgent), Ord(UseProxy), PProxy, PProxyBypass, 0);
  Win32Check(Assigned(hInt));
  try
    if ConnectTimeout > 0 then InternetSetOption(hInt, INTERNET_OPTION_CONNECT_TIMEOUT, @ConnectTimeout, sizeof(ConnectTimeout));
    if SendTimeout > 0    then InternetSetOption(hInt, INTERNET_OPTION_SEND_TIMEOUT,    @SendTimeout,    sizeof(SendTimeout));
    if ReceiveTimeout > 0 then InternetSetOption(hInt, INTERNET_OPTION_RECEIVE_TIMEOUT, @ReceiveTimeout, sizeof(ReceiveTimeout));

    if Length(Self.UserName) = 0 then begin
      PUserName := nil;
    end else begin
      PUserName := PChar(Self.UserName);
    end;
    if Length(Self.Password) = 0 then begin
      PPassword := nil;
    end else begin
      PPassword := PChar(Self.Password);
    end;

    { Try to connect, then send the request }
    hConn := InternetConnect(hInt, PChar(Hostname), Self.Port, PUserName, PPassword, INTERNET_SERVICE_HTTP, 0, 1);
    Win32Check(Assigned(hConn));
    try
      if Self.Port = INTERNET_DEFAULT_HTTPS_PORT then begin
        Flags := Flags or INTERNET_FLAG_SECURE or INTERNET_FLAG_IGNORE_CERT_CN_INVALID or INTERNET_FLAG_IGNORE_CERT_DATE_INVALID;
      end;
      FhReq := HttpOpenRequest(hConn, PChar(Verb), PChar(Resource), nil, nil, nil, Flags, 1);
      Win32Check(Assigned(FhReq));
      try
        Size := INTERNET_MAX_URL_LENGTH;
        SetLength(FURL, Size);
        if not InternetQueryOption(FhReq, INTERNET_OPTION_URL, PChar(FURL), Size) then begin
          if GetLastError = ERROR_INSUFFICIENT_BUFFER then begin
            SetLength(FURL, Size);
            Win32Check(InternetQueryOption(FhReq, INTERNET_OPTION_URL, PChar(FURL), Size));
          end else begin
            RaiseLastOSError;
          end;
        end;
        FURL := StrPas(PChar(FURL));

        if Assigned(FOnProgress) then begin
          FOnProgress(Self, scUploading, 0, 0, Cancel);
          if Cancel then
            Exit;
        end;

        Win32Check(HttpSendRequest(FhReq,
                                   PChar(FRequestHeaders.Text), Length(FRequestHeaders.Text),
                                   Data, DataSize));

        { Try to get the content-length }
        if not QueryInfoInteger(HTTP_QUERY_CONTENT_LENGTH, TotalBytesToRead) then
          TotalBytesToRead := 0;

        FResponseStream := TMemoryStream.Create;
        Buffer := TMemoryStream.Create;
        try
          TotalBytesRead := 0;
          Buffer.SetSize(READBUFFERSIZE);
          repeat
            Sleep(0);
            if not InternetReadFile(FhReq, Buffer.Memory, READBUFFERSIZE, BytesRead) then begin
              Break;
            end;
            if BytesRead > 0 then begin
              Buffer.Position := 0;
              FResponseStream.CopyFrom(Buffer, Min(BytesRead, READBUFFERSIZE));
              Inc(TotalBytesRead, BytesRead);
              if Assigned(FOnProgress) then begin
                FOnProgress(Self, scDownloading, TotalBytesRead, TotalBytesToRead, Cancel);
                if Cancel then Exit;
              end;
            end;
          until (BytesRead = 0);
        finally
          Buffer.Free;
          FResponseStream.Position := 0;
        end;

        { Read the response status and headers }
        FResponseStatus := QueryInfoInteger(HTTP_QUERY_STATUS_CODE);
        FResponseStatusText := QueryInfoString(HTTP_QUERY_STATUS_TEXT);
        ReadResponseHeaders;

      finally
        InternetCloseHandle(FhReq);
      end;
    finally
      InternetCloseHandle(hConn);
    end;
  finally
    InternetCloseHandle(hInt);
  end;

  if Assigned(FOnProgress) then
    FOnProgress(Self, scFinished, TotalBytesRead, TotalBytesToRead, Cancel);

  Result := FResponseStatus;
end {THttpClient.SendRequestAndGetResponse};


{ ------------------------------------------------------------------------------------------------ }
function THttpClient.QueryInfoInteger(const InfoFlag: cardinal): cardinal;
begin
  Win32Check(QueryInfoInteger(InfoFlag, Result));
end {THttpClient.QueryInfoInteger};
{ ------------------------------------------------------------------------------------------------ }
function THttpClient.QueryInfoInteger(const InfoFlag: cardinal; out Value: cardinal): boolean;
var
  Index, BufSize: Cardinal;
begin
  Index := 0;
  bufsize := sizeOf(Value);
  Result := HttpQueryInfo(FhReq, InfoFlag or HTTP_QUERY_FLAG_NUMBER, @Value, BufSize, Index);
end {THttpClient.QueryInfoInteger};

{ ------------------------------------------------------------------------------------------------ }
function THttpClient.QueryInfoString(const InfoFlag: cardinal): string;
begin
  Win32Check(QueryInfoString(InfoFlag, Result));
end {THttpClient.QueryInfoString};
{ ------------------------------------------------------------------------------------------------ }
function THttpClient.QueryInfoString(const InfoFlag: cardinal; out Value: string): Boolean;
var
  BufSize, Index: cardinal;
  i: byte;
begin
  Result := True;
  Index := 0;
  bufsize := READBUFFERSIZE;
  for i := 0 to 1 do begin
    SetLength(Value, bufsize div SizeOf(Char));
    if not HttpQueryInfo(FhReq, InfoFlag, PChar(Value), bufsize, Index) then begin
      case GetLastError of
        ERROR_INSUFFICIENT_BUFFER: begin
          // bufsize now contains the required size; just go to the next iteration.
        end;
        ERROR_HTTP_HEADER_NOT_FOUND: begin
          // no more headers; just return the current result
          SetLength(Value, bufsize div SizeOf(Char));
          Break;
        end;
        else begin
          Result := False;
          Break;
        end;
      end;
    end else begin
      // HttpQueryInfo was successful
      SetLength(Value, bufsize div SizeOf(Char));
      Break;
    end;
  end {for};
end {THttpClient.QueryInfoString};

{ ------------------------------------------------------------------------------------------------ }
procedure THttpClient.ReadResponseHeaders;
var
  Headers, Header: string;
  i, Offset: integer;
begin
  Headers := QueryInfoString(HTTP_QUERY_RAW_HEADERS);
  Header := StringOfChar(#0, Length(Headers));
  FResponseHeaders := TStringList.Create;
  FResponseHeaders.NameValueSeparator := ':';
  FResponseHeaders.CaseSensitive := False;

  Offset := 0;
  for i := 1 to Length(Headers) - 1 do begin
    if Headers[i] = #0 then begin
      SetLength(Header, i - Offset - 1);
      if Length(Header) = 0 then begin
        Break;
      end;
      FResponseHeaders.Add(Header);
      Header := StringOfChar(#0, Length(Headers) - i);
      Offset := i;
    end else begin
      Header[i - Offset] := Headers[i];
    end;
  end;
  if (Length(Header) > 0) and (Header[1] <> #0) then begin
    Offset := Pos(#0, Header);
    if Offset > 0 then begin
      FResponseHeaders.Add(Copy(Header, 1, Offset - 1));
    end else begin
      FResponseHeaders.Add(Header);
    end;
  end;
end {THttpClient.ReadResponseHeaders};

{ ------------------------------------------------------------------------------------------------ }
function THttpClient.GetResponseString: string;
var
  ContentType, Charset: string;
  Encoding: TEncoding;
  Params: TStringList;
  SS: TStringStream;
  CharPos: Integer;
begin
  if Assigned(FResponseStream) and (FResponseStream.Size > 0) then begin
    // First, determine whether or not the response specifies a character set
    
    Encoding := TEncoding.Default; // Default to ANSI
    ContentType := FResponseHeaders.Values['Content-Type'];
    CharPos := Pos(';', ContentType);
    if CharPos > 0 then begin
      Params := TStringList.Create;
      try
        Params.Delimiter := ',';
        Params.NameValueSeparator := '=';
        Params.DelimitedText := Copy(ContentType, CharPos + 1);
        Charset := Params.Values['charset'];
      finally
        Params.Free;
      end;
      if Charset <> '' then begin
        Encoding := TEncoding.GetEncoding(Charset);
      end;
    end;
    
    // Now use the given encoding to decode the content into a string
    SS := TStringStream.Create('', Encoding);
    try
      SS.CopyFrom(FResponseStream, 0);
      Result := SS.DataString;
    finally
      SS.Free;
    end;
  end else begin
    Result := '';
  end;
end {THttpClient.GetResponseString};

end.

Added src/L_VersionInfoW.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
unit L_VersionInfoW;

interface

uses
  Windows, SysUtils;

type
  TFileVersionInfo = class
  private
    { Private declarations }
    FFilename         : WideString;
    FHasVersionInfo   : boolean;

    FCompanyName      : WideString;
    FFileDescription  : WideString;
    FFileVersion      : WideString;
    FInternalname     : WideString;
    FLegalCopyright   : WideString;
    FLegalTradeMarks  : WideString;
    FOriginalFilename : WideString;
    FProductName      : WideString;
    FProductVersion   : WideString;
    FComments         : WideString;
    FMajorVersion     : Word;
    FMinorVersion     : Word;
    FRevision          : Word;
    FBuild            : Word;

    procedure SetFileName(AFileName: WideString);
  protected
    { Protected declarations }
  public
    { Public declarations }
    constructor Create(AFileName: WideString);
    destructor  Destroy; override;

    property FileName         : WideString  read FFileName          write SetFileName;
    property HasVersionInfo   : boolean     read FHasVersionInfo;
  published
    { Published declarations }
    property CompanyName      : WideString  read FCompanyName;
    property FileDescription  : WideString  read FFileDescription;
    property FileVersion      : WideString  read FFileVersion;
    property Internalname     : WideString  read FInternalname;
    property LegalCopyright   : WideString  read FLegalCopyright;
    property LegalTradeMarks  : WideString  read FLegalTradeMarks;
    property OriginalFilename : WideString  read FOriginalFilename;
    property ProductName      : WideString  read FProductName;
    property ProductVersion   : WideString  read FProductVersion;
    property Comments         : WideString  read FComments;
    property MajorVersion     : Word        read FMajorVersion;
    property MinorVersion     : Word        read FMinorVersion;
    property Revision         : Word        read FRevision;
    property Build            : Word        read FBuild;
  end;

implementation

type
  TLangAndCP = record
    wLanguage : word;
    wCodePage : word;
  end;
  PLangAndCP = ^TLangAndCP;

constructor TFileVersionInfo.Create(AFileName: WideString);
begin
  inherited Create;
  SetFileName(AFileName);
end;

destructor TFileVersionInfo.Destroy;
begin
  inherited Destroy;
end;

procedure TFileVersionInfo.SetFileName(AFileName: WideString);
var
  Dummy     : cardinal;
  BufferSize: integer;
  Buffer    : Pointer;
  Lang      : PLangAndCP;
  SubBlock  : WideString;
  InfoBlock : VS_FIXEDFILEINFO;
  InfoPtr   : Pointer;
  function QueryValue(AName: WideString): WideString;
  var
    Value   : PWChar;
  begin
    SubBlock := WideFormat('\\StringFileInfo\\%.4x%.4x\\%s', [Lang.wLanguage, Lang.wCodePage, AName]);
    VerQueryValueW(Buffer, PWChar(SubBlock), Pointer(Value), Dummy);
    Result := WideString(Value);
  end;
begin
  FFilename := AFileName;

  BufferSize := GetFileVersionInfoSizeW(PWChar(AFileName), Dummy);
  FHasVersionInfo := (Buffersize > 0);
  if FHasVersionInfo then begin
    Buffer := AllocMem(BufferSize);
    try
      GetFileVersionInfoW(PWChar(AFileName),0,BufferSize,Buffer);

      SubBlock := '\\VarFileInfo\\Translation';
      VerQueryValueW(Buffer, PWChar(SubBlock), Pointer(Lang), Dummy);

      FCompanyName      := QueryValue('CompanyName');
      FFileDescription  := QueryValue('FileDescription');
      FFileVersion      := QueryValue('FileVersion');
      FInternalName     := QueryValue('InternalName');
      FLegalCopyright   := QueryValue('LegalCopyright');
      FLegalTradeMarks  := QueryValue('LegalTradeMarks');
      FOriginalFilename := QueryValue('OriginalFilename');
      FProductName      := QueryValue('ProductName');
      FProductVersion   := QueryValue('ProductVersion');
      FComments         := QueryValue('Comments');

      VerQueryValue(Buffer, '\', InfoPtr, Dummy);
      Move(InfoPtr^, InfoBlock, SizeOf(VS_FIXEDFILEINFO));
      FMajorVersion := InfoBlock.dwFileVersionMS shr 16;
      FMinorVersion := InfoBlock.dwFileVersionMS and 65535;
      FRevision     := InfoBlock.dwFileVersionLS shr 16;
      FBuild        := InfoBlock.dwFileVersionLS and 65535;
    finally
      FreeMem(Buffer,BufferSize);
    end;
  end
  else begin
    FCompanyname      := '';
    FFileDescription  := '';
    FFileVersion      := '';
    FInternalname     := '';
    FLegalCopyright   := '';
    FLegalTradeMarks  := '';
    FOriginalFilename := '';
    FProductName      := '';
    FProductVersion   := '';
    FComments         := '';
    FMajorVersion     := 0;
    FMinorVersion     := 0;
    FRevision         := 0;
    FBuild            := 0;
  end;
end;


end.

Added src/NativeXml/NativeXml.inc.













































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
{ unit NativeXml.inc

  Nativexml a small-footprint implementation to read and write XML documents
  natively from Delpi code. NativeXml has very fast parsing speeds.

  Author: Nils Haeck M.Sc.
  Copyright (c) 2007 - 2010 Simdesign B.V.

  It is NOT allowed under ANY circumstances to publish, alter or copy this code
  without accepting the license conditions in accompanying LICENSE.txt
  first!

  This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
  ANY KIND, either express or implied.

  Please visit http://www.simdesign.nl/xml.html for more information.
}
// Delphi and BCB versions

// Freepascal (MK)
{$ifdef FPC}
  {$MODE DELPHI}
  {$define D7UP}
{$endif FPC}
//Delphi 7
{$ifdef VER150}
  {$define D7UP}
{$endif}
//Delphi 8
{$ifdef VER160}
  {$define D7UP}
{$endif}
// Delphi 2005
{$ifdef VER170}
  {$define D7UP}
{$endif}
// Delphi 2006
{$ifdef VER180}
  {$define D7UP}
{$endif}
// Delphi 2007 - NET
{$ifdef VER190}
  {$define D7UP}
{$endif}
// Delphi 2009
{$ifdef VER200}
  {$define D7UP}
  {$define D12UP}
{$endif}
// Delphi 2010
{$ifdef VER210}
  {$define D7UP}
  {$define D12UP}
{$endif}
// Delphi XE
{$ifdef VER220}
  {$define D7UP}
  {$define D12UP}
  {$define D15UP}
{$endif}
// Delphi XE2 / 16
{$ifdef VER230}
  {$define D7UP}
  {$define D10UP}
  {$define D12UP}
  {$define D15UP}
{$endif}

// Delphi XE3 / 17
{$ifdef VER240}
  {$define D7UP}
  {$define D10UP}
  {$define D12UP}
  {$define D15UP}
{$endif}

// Delphi XE4 / 18
{$ifdef VER250}
  {$define D7UP}
  {$define D10UP}
  {$define D12UP}
  {$define D15UP}
{$endif}

// Delphi XE5 / 19
{$ifdef VER260}
  {$define D7UP}
  {$define D10UP}
  {$define D12UP}
  {$define D15UP}
{$endif}

// Uncomment to save memory space for large documents if you don't need tags.
// Tags are an additional integer field that can be used by the application.
{$define USETAGS}

// uncomment if you do not want to include the Graphics unit.
{.$define USEGRAPHICS}

// uncomment if you do not want line number/position info from the source file
{$define SOURCEPOS}

Added src/NativeXml/NativeXml.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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
{ unit NativeXml

  This is a small-footprint implementation to read and write XML documents
  natively from Delpi code.

  You can use this code to read XML documents from files, streams or strings.
  The load routine generates events that can be used to display load progress
  on the fly.

  Note: any external encoding (ANSI, UTF16, etc) is converted to an internal
  encoding that is ANSI or UTF8. When the loaded document is ANSI based,
  the encoding will be ANSI, in other cases (UTF8, UTF16) the encoding
  will be UTF8.

  Original Author: Nils Haeck M.Sc. (n.haeck@simdesign.nl)
  Original Date: 01 Apr 2003
  Version: see below
  Copyright (c) 2003-2010 Simdesign BV
  Contributor(s): Stefan Glienke

  It is NOT allowed under ANY circumstances to publish or copy this code
  without accepting the license conditions in accompanying LICENSE.txt
  first!

  This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
  ANY KIND, either express or implied.

  Please visit http://www.simdesign.nl/xml.html for more information.
}
unit NativeXml;

interface

{$i nativexml.inc}

uses
  Windows,
  {$IFDEF CLR}
  System.Text,
  {$ENDIF}
  {$IFDEF USEGRAPHICS}
  {$IFDEF LINUX}
  QGraphics,
  {$ELSE}
  Graphics,
  {$ENDIF}
  {$ENDIF}
  Classes,
  SysUtils;

const

  // Current version of the NativeXml unit
  cNativeXmlVersion = '3.10';

// cross-platform pointer type
type
  {$IFDEF CLR}
  TPointer = TObject;
  {$ELSE}
  TPointer = Pointer;
  {$ENDIF}

{$IFDEF D12UP}
// Delphi 2009 and up
type
  UnicodeChar = Char;
  PUnicodeChar = PChar;
{$ELSE}
// Delphi 2007 and below
type
  UnicodeString = WideString;
  UnicodeChar = WideChar;
  PUnicodeChar = PWideChar;
  RawByteString = AnsiString;
{$ENDIF}

type

  // Note on TNativeXml.Format:
  // - xfReadable (default) to be able to read the xml file with a standard editor.
  // - xfCompact to save the xml fully compliant and at smallest size
  TXmlFormatType = (
    xfReadable,   // Save in readable format with CR-LF and indents
    xfCompact     // Save without any control chars except LF after declarations
  );

  // TXmlElementType enumerates the different kinds of elements that can be found
  // in the XML document.
  TXmlElementType = (
    xeNormal,      // Normal element <name {attr}>[value][sub-elements]</name>
    xeComment,     // Comment <!--{comment}-->
    xeCData,       // literal data <![CDATA[{data}]]>
    xeDeclaration, // XML declaration <?xml{declaration}?>
    xeStylesheet,  // Stylesheet <?xml-stylesheet{stylesheet}?>
    xeDoctype,     // DOCTYPE DTD declaration <!DOCTYPE{spec}>
    xeElement,     // <!ELEMENT >
    xeAttList,     // <!ATTLIST >
    xeEntity,      // <!ENTITY >
    xeNotation,    // <!NOTATION >
    xeExclam,      // Any <!data>
    xeQuestion,    // Any <?data?>
    xeCharData,    // character data in a node
    xeUnknown      // Any <data>
  );

  // Choose what kind of binary encoding will be used when calling
  // TXmlNode BufferRead and BufferWrite.
  TBinaryEncodingType = (
    xbeBinHex,  { With this encoding, each byte is stored as a hexadecimal
                  number, e.g. 0 = 00 and 255 = FF.                        }
    xbeBase64   { With this encoding, each group of 3 bytes are stored as 4
                  characters, requiring 64 different AnsiCharacters.}
  );

  // Definition of different methods of String encoding.
  TStringEncodingType = (
    seAnsi,      // General 8 bit encoding, encoding must be determined from encoding declaration
    seUCS4BE,    // UCS-4 Big Endian
    seUCS4LE,    // UCS-4 Little Endian
    seUCS4_2143, // UCS-4 unusual octet order (2143)
    seUCS4_3412, // UCS-4 unusual octet order (3412)
    se16BitBE,   // General 16 bit Big Endian, encoding must be determined from encoding declaration
    se16BitLE,   // General 16 bit Little Endian, encoding must be determined from encoding declaration
    seUTF8,      // UTF-8
    seUTF16BE,   // UTF-16 Big Endian
    seUTF16LE,   // UTF-16 Little Endian
    seEBCDIC     // EBCDIC flavour
  );

  TXmlCompareOption = (
    xcNodeName,
    xcNodeType,
    xcNodeValue,
    xcAttribCount,
    xcAttribNames,
    xcAttribValues,
    xcChildCount,
    xcChildNames,
    xcChildValues,
    xcRecursive
  );

  TXmlCompareOptions = set of TXmlCompareOption;

const

  xcAll: TXmlCompareOptions = [xcNodeName, xcNodeType, xcNodeValue, xcAttribCount,
    xcAttribNames, xcAttribValues, xcChildCount, xcChildNames, xcChildValues,
    xcRecursive];

var

  // XML Defaults

  cDefaultEncodingString:          UTF8String          = 'UTF-8';
  cDefaultExternalEncoding:        TStringEncodingType = seUTF8;
  cDefaultVersionString:           UTF8String          = '1.0';
  cDefaultXmlFormat:               TXmlFormatType      = xfCompact;
  cDefaultWriteOnDefault:          boolean             = True;
  cDefaultBinaryEncoding:          TBinaryEncodingType = xbeBase64;
  cDefaultIndentString:            UTF8String          = '  ';
  cDefaultDropCommentsOnParse:     boolean             = False;
  cDefaultUseFullNodes:            boolean             = False;
  cDefaultUseLocalBias:            boolean             = False;
  cDefaultFloatAllowScientific:    boolean             = True;
  cDefaultFloatSignificantDigits:  integer             = 9;

type

  TXmlNode = class;
  TNativeXml = class;
  TsdCodecStream = class;

  // An event that is based on the TXmlNode object Node.
  TXmlNodeEvent = procedure(Sender: TObject; Node: TXmlNode) of object;

  // An event that is used to indicate load or save progress.
  TXmlProgressEvent = procedure(Sender: TObject; Size: integer) of object;

  // This event is used in the TNativeXml.OnNodeCompare event, and should
  // return -1 if Node1 < Node2, 0 if Node1 = Node2 and 1 if Node1 > Node2.
  TXmlNodeCompareEvent = function(Sender: TObject; Node1, Node2: TXmlNode; Info: TPointer): integer of object;

  // Pass a function of this kind to TXmlNode.SortChildNodes. The function should
  // return -1 if Node1 < Node2, 0 if Node1 = Node2 and 1 if Node1 > Node2.
  TXMLNodeCompareFunction = function(Node1, Node2: TXmlNode; Info: TPointer): integer;

  // Very simple autonomous stringlist that holds the list of attributes in the node
  TsdUTF8StringList = class(TPersistent)
  private
    FItems: array of UTF8String;
    FCount: integer;
    function GetItems(Index: integer): UTF8String;
    procedure SetItems(Index: integer; const Value: UTF8String);
    function GetValues(const Name: UTF8String): UTF8String;
    function GetNames(Index: integer): UTF8String;
    procedure SetValues(const Name, Value: UTF8String);
    function GetText: UTF8String;
  public
    function Add(const S: UTF8String): integer;
    procedure Assign(Source: TPersistent); override;
    procedure Clear;
    procedure Delete(Index: Integer);
    function IndexOfName(const Name: UTF8String): integer;
    property Count: integer read FCount;
    property Items[Index: integer]: UTF8String read GetItems write SetItems; default;
    property Names[Index: integer]: UTF8String read GetNames;
    property Values[const Name: UTF8String]: UTF8String read GetValues write SetValues;
    property Text: UTF8String read GetText;
  end;

  // The TXmlNode represents an element in the XML file. Each TNativeXml holds
  // one Root element. Under ths root element, sub-elements can be nested (there
  // is no limit on how deep). Property ElementType defines what kind of element
  // this node is.
  TXmlNode = class(TPersistent)
  private
    FName: UTF8String;              // The element name
    FValue: UTF8String;             // The *escaped* value
    FAttributes: TsdUTF8StringList; // List with attributes
    FNodes: TList;                  // These are the child elements
    FParent: TXmlNode;              // Pointer to parent element
    FDocument: TNativeXml;          // Pointer to parent XmlDocument
    FElementType: TXmlElementType;  // The type of element
    FTag: integer;                  // A value the developer can use
    function AbortParsing: boolean;
    function GetValueAsString: UTF8String;
    procedure SetAttributeName(Index: integer; const Value: UTF8String);
    procedure SetAttributeValue(Index: integer; const Value: UTF8String);
    procedure SetValueAsString(const AValue: UTF8String);
    function GetIndent: UTF8String;
    function GetLineFeed: UTF8String;
    function GetTreeDepth: integer;
    function GetAttributeCount: integer;
    function GetAttributePair(Index: integer): UTF8String;
    function GetAttributeName(Index: integer): UTF8String;
    function GetAttributeValue(Index: integer): UTF8String;
    function GetWriteOnDefault: boolean;
    function GetBinaryEncoding: TBinaryEncodingType;
    function GetCascadedName: UTF8String;
    function QualifyAsDirectNode: boolean;
    procedure SetName(const Value: UTF8String);
    function GetFullPath: UTF8String;
    procedure SetBinaryEncoding(const Value: TBinaryEncodingType);
    function GetBinaryString: RawByteString;
    procedure SetBinaryString(const Value: RawByteString);
    function UseFullNodes: boolean;
    function UseLocalBias: Boolean;
    function GetValueAsUnicodeString: UnicodeString;
    procedure SetValueAsUnicodeString(const Value: UnicodeString);
    function GetAttributeByName(const AName: UTF8String): UTF8String;
    procedure SetAttributeByName(const AName, Value: UTF8String);
    function GetValueAsInteger: integer;
    procedure SetValueAsInteger(const Value: integer);
    function GetValueAsFloat: double;
    procedure SetValueAsFloat(const Value: double);
    function GetValueAsDateTime: TDateTime;
    procedure SetValueAsDateTime(const Value: TDateTime);
    function GetValueAsBool: boolean;
    procedure SetValueAsBool(const Value: boolean);
    function GetValueAsInt64: int64;
    procedure SetValueAsInt64(const Value: int64);
    procedure CheckCreateAttributesList;
    function GetAttributeValueAsUnicodeString(Index: integer): UnicodeString;
    procedure SetAttributeValueAsUnicodeString(Index: integer;
      const Value: UnicodeString);
    function GetAttributeValueAsInteger(Index: integer): integer;
    procedure SetAttributeValueAsInteger(Index: integer;
      const Value: integer);
    function GetAttributeByNameWide(const AName: UTF8String): UnicodeString;
    procedure SetAttributeByNameWide(const AName: UTF8String;
      const Value: UnicodeString);
    function GetTotalNodeCount: integer;
    function FloatSignificantDigits: integer;
    function FloatAllowScientific: boolean;
    function GetAttributeValueDirect(Index: integer): UTF8String;
    procedure SetAttributeValueDirect(Index: integer; const Value: UTF8String);
  protected
    function CompareNodeName(const NodeName: UTF8String): integer;
    procedure DeleteEmptyAttributes;
    function GetNodes(Index: integer): TXmlNode; virtual;
    function GetNodeCount: integer; virtual;
    procedure ParseTag(const AValue: UTF8String; TagStart, TagClose: integer);
    procedure ReadFromStream(S: TStream); virtual;
    procedure ReadFromString(const AValue: UTF8String); virtual;
    procedure ResolveEntityReferences;
    function UnescapeString(const AValue: UTF8String): UTF8String; virtual;
    function WriteInnerTag: UTF8String; virtual;
    procedure WriteToStream(S: TStream); virtual;
    procedure ChangeDocument(ADocument: TNativeXml);
  public
    // Create a new TXmlNode object. ADocument must be the TNativeXml that is
    // going to hold this new node.
    constructor Create(ADocument: TNativeXml); virtual;
    // \Create a new TXmlNode with name AName. ADocument must be the TNativeXml
    // that is going to hold this new node.
    constructor CreateName(ADocument: TNativeXml; const AName: UTF8String); virtual;
    // \Create a new TXmlNode with name AName and UTF8String value AValue. ADocument
    // must be the TNativeXml that is going to hold this new node.
    constructor CreateNameValue(ADocument: TNativeXml; const AName, AValue: UTF8String); virtual;
    // \Create a new TXmlNode with XML element type AType. ADocument must be the
    // TNativeXml that is going to hold this new node.
    constructor CreateType(ADocument: TNativeXml; AType: TXmlElementType); virtual;
    // Use Assign to assign another TXmlNode to this node. This means that all
    // properties and subnodes from the Source TXmlNode are copied to the current
    // node. You can also Assign a TNativeXml document to the node, in that case
    // the RootNodeList property of the TNativeXml object will be copied.
    procedure Assign(Source: TPersistent); override;
    // Call Delete to delete this node completely from the parent node list. This
    // call only succeeds if the node has a parent. It has no effect when called for
    // the root node.
    procedure Delete; virtual;
    // \Delete all nodes that are empty (this means, which have no subnodes, no
    // attributes, and no value assigned). This procedure works recursively.
    procedure DeleteEmptyNodes;
    // Destroy a TXmlNode object. This will free the child node list automatically.
    // Never call this method directly. All TXmlNodes in the document will be
    // recursively freed when TNativeXml.Free is called.
    destructor Destroy; override;
    // Use this method to add an integer attribute to the node.
    procedure AttributeAdd(const AName: UTF8String; AValue: integer); overload;
    // Use this method to add a string attribute with value AValue to the node.
    procedure AttributeAdd(const AName, AValue: UTF8String); overload;
    // Use this method to delete the attribute at Index in the list. Index must be
    // equal or greater than 0, and smaller than AttributeCount. Using an index
    // outside of that range has no effect.
    procedure AttributeDelete(Index: integer);
    // Switch position of the attributes at Index1 and Index2.
    procedure AttributeExchange(Index1, Index2: integer);
    // Use this method to find the index of an attribute with name AName.
    function AttributeIndexByname(const AName: UTF8String): integer;
    // \Clear all attributes from the current node.
    procedure AttributesClear; virtual;
    // Use this method to read binary data from the node into Buffer with a length of Count.
    procedure BufferRead(var Buffer{$IFDEF CLR}: TBytes{$ENDIF}; Count: Integer); virtual;
    // Use this method to write binary data in Buffer with a length of Count to the
    // current node. The data will appear as text using either BinHex or Base64
    // method) in the final XML document.
    // Notice that NativeXml does only support up to 2Gb bytes of data per file,
    // so do not use this option for huge files. The binary encoding method (converting
    // binary data into text) can be selected using property BinaryEncoding.
    // xbeBase64 is most efficient, but slightly slower. Always use identical methods
    // for reading and writing.
    procedure BufferWrite(const Buffer{$IFDEF CLR}: TBytes{$ENDIF}; Count: Integer); virtual;
    // Returns the length of the data in the buffer, once it would be decoded by
    // method xbeBinHex or xbeBase64. If BinaryEncoding is xbeSixBits, this function
    // cannot be used. The length of the unencoded data is determined from the
    // length of the encoded data. For xbeBinHex this is trivial (just half the
    // length), for xbeBase64 this is more difficult (must use the padding characters)
    function BufferLength: integer; virtual;
    // Clear all child nodes and attributes, and the name and value of the current
    // XML node. However, the node is not deleted. Call Delete instead for that.
    procedure Clear; virtual;
    // Find the first node which has name NodeName. Contrary to the NodeByName
    // function, this function will search the whole subnode tree, using the
    // DepthFirst method. It is possible to search for a full path too, e.g.
    // FoundNode := MyNode.FindNode('/Root/SubNode1/SubNode2/ThisNode');
    function FindNode(const NodeName: UTF8String): TXmlNode;
    // Find all nodes which have name NodeName. Contrary to the NodesByName
    // function, this function will search the whole subnode tree. If you use
    // a TXmlNodeList for the AList parameter, you don't need to cast the list
    // items to TXmlNode.
    procedure FindNodes(const NodeName: UTF8String; const AList: TList);
    // Use FromAnsiString to convert a normal ANSI String to a UTF8String for the node
    // (name, value, attributes). In TNativeXml the ANSI Characters are encoded
    // into UTF8.
    function FromAnsiString(const s: AnsiString): UTF8String;
    // Use FromUnicodeString to convert UnicodeString to a UTF8String for the node (name, value,
    // attributes).
    function FromUnicodeString(const W: UnicodeString): UTF8String;
    // Use HasAttribute to determine if the node has an attribute with name AName.
    function HasAttribute(const AName: UTF8String): boolean; virtual;
    // This function returns the index of this node in the parent's node list.
    // If Parent is not assigned, this function returns -1.
    function IndexInParent: integer;
    // This function returns True if the node has no subnodes and no attributes,
    // and if the node Name and value are empty.
    function IsClear: boolean; virtual;
    // This function returns True if the node has no subnodes and no attributes,
    // and if the node value is empty.
    function IsEmpty: boolean; virtual;
    function IsEqualTo(ANode: TXmlNode; Options: TXmlCompareOptions; MismatchNodes: TList = nil): boolean;
    // Add the node ANode as a new subelement in the nodelist. The node will be
    // added in position NodeCount (which will be returned).
    function NodeAdd(ANode: TXmlNode): integer; virtual;
    // This function returns a pointer to the first subnode that has an attribute with
    // name AttribName and value AttribValue. If ShouldRecurse = True (default), the
    // function works recursively, using the depthfirst method.
    function NodeByAttributeValue(const NodeName, AttribName, AttribValue: UTF8String;
      ShouldRecurse: boolean = True): TXmlNode;
    // Return a pointer to the first subnode with this Elementype, or return nil
    // if no subnode with that type is found.
    function NodeByElementType(ElementType: TXmlElementType): TXmlNode;
    // Return a pointer to the first subnode in the nodelist that has name AName.
    // If no subnodes with AName are found, the function returns nil.
    function NodeByName(const AName: UTF8String): TXmlNode; virtual;
    // \Delete the subnode at Index. The node will also be freed, so do not free the
    // node in the application.
    procedure NodeDelete(Index: integer); virtual;
    // Switch position of the nodes at Index1 and Index2.
    procedure NodeExchange(Index1, Index2: integer);
    // Extract the node ANode from the subnode list. The node will no longer appear
    // in the subnodes list, so the application is responsible for freeing ANode later.
    function NodeExtract(ANode: TXmlNode): TXmlNode; virtual;
    // This function returns a pointer to the first node with AName. If this node
    // is not found, then it creates a new node with AName and returns its pointer.
    function NodeFindOrCreate(const AName: UTF8String): TXmlNode; virtual;
    // Find the index of the first subnode with name AName.
    function NodeIndexByName(const AName: UTF8String): integer; virtual;
    // Find the index of the first subnode with name AName that appears after or on
    // the index AFrom. This function can be used in a loop to retrieve all nodes
    // with a certain name, without using a helper list. See also NodesByName.
    function NodeIndexByNameFrom(const AName: UTF8String; AFrom: integer): integer; virtual;
    // Call NodeIndexOf to get the index for ANode in the Nodes array. The first
    // node in the array has index 0, the second item has index 1, and so on. If
    // a node is not in the list, NodeIndexOf returns -1.
    function NodeIndexOf(ANode: TXmlNode): integer;
    // Insert the node ANode at location Index in the list.
    procedure NodeInsert(Index: integer; ANode: TXmlNode); virtual;
    // \Create a new node with AName, add it to the subnode list, and return a
    // pointer to it.
    function NodeNew(const AName: UTF8String): TXmlNode; virtual;
    // \Create a new node with AName, and insert it into the subnode list at location
    // Index, and return a pointer to it.
    function NodeNewAtIndex(Index: integer; const AName: UTF8String): TXmlNode; virtual;
    // Call NodeRemove to remove a specific node from the Nodes array when its index
    // is unknown. The value returned is the index of the item in the Nodes array
    // before it was removed. After an item is removed, all the items that follow
    // it are moved up in index position and the NodeCount is reduced by one.
    function NodeRemove(ANode: TxmlNode): integer;
    // \Clear (and free) the complete list of subnodes.
    procedure NodesClear; virtual;
    // Use this procedure to retrieve all nodes that have name AName. Pointers to
    // these nodes are added to the list in AList. AList must be initialized
    // before calling this procedure. If you use a TXmlNodeList you don't need
    // to cast the list items to TXmlNode.
    procedure NodesByName(const AName: UTF8String; const AList: TList);
    // Find the attribute with AName, and convert its value to a boolean. If the
    // attribute is not found, or cannot be converted, the default ADefault will
    // be returned.
    function ReadAttributeBool(const AName: UTF8String; ADefault: boolean = False): boolean; virtual;
    function ReadAttributeDateTime(const AName: UTF8String; ADefault: TDateTime = 0): TDateTime; virtual;
    // Find the attribute with AName, and convert its value to an integer. If the
    // attribute is not found, or cannot be converted, the default ADefault will
    // be returned.
    function ReadAttributeInteger(const AName: UTF8String; ADefault: integer = 0): integer; virtual;
    // Find the attribute with AName, and convert its value to an int64. If the
    // attribute is not found, or cannot be converted, the default ADefault will
    // be returned.
    function ReadAttributeInt64(const AName: UTF8String; ADefault: int64 = 0): int64; virtual;
    // Find the attribute with AName, and convert its value to a float. If the
    // attribute is not found, or cannot be converted, the default ADefault will
    // be returned.
    function ReadAttributeFloat(const AName: UTF8String; ADefault: double = 0): double;
    function ReadAttributeString(const AName: UTF8String; const ADefault: UTF8String = ''): UTF8String; virtual;
    // Read the subnode with AName and convert it to a boolean value. If the
    // subnode is not found, or cannot be converted, the boolean ADefault will
    // be returned.
    function ReadBool(const AName: UTF8String; ADefault: boolean = False): boolean; virtual;
    {$IFDEF USEGRAPHICS}
    // Read the properties Color and Style for the TBrush object ABrush from the
    // subnode with AName.
    procedure ReadBrush(const AName: UTF8String; ABrush: TBrush); virtual;
    // Read the subnode with AName and convert its value to TColor. If the
    // subnode is not found, or cannot be converted, ADefault will be returned.
    function ReadColor(const AName: UTF8String; ADefault: TColor = clBlack): TColor; virtual;
    // Read the properties \Name, Color, Size and Style for the TFont object AFont
    // from the subnode with AName.
    procedure ReadFont(const AName: UTF8String; AFont: TFont); virtual;
    // Read the properties Color, Mode, Style and Width for the TPen object APen
    // from the subnode with AName.
    procedure ReadPen(const AName: UTF8String; APen: TPen); virtual;
    {$ENDIF}
    // Read the subnode with AName and convert its value to TDateTime. If the
    // subnode is not found, or cannot be converted, ADefault will be returned.
    function ReadDateTime(const AName: UTF8String; ADefault: TDateTime = 0): TDateTime; virtual;
    // Read the subnode with AName and convert its value to a double. If the
    // subnode is not found, or cannot be converted, ADefault will be returned.
    function ReadFloat(const AName: UTF8String; ADefault: double = 0.0): double; virtual;
    // Read the subnode with AName and convert its value to an int64. If the
    // subnode is not found, or cannot be converted, ADefault will be returned.
    function ReadInt64(const AName: UTF8String; ADefault: int64 = 0): int64; virtual;
    // Read the subnode with AName and convert its value to an integer. If the
    // subnode is not found, or cannot be converted, ADefault will be returned.
    function ReadInteger(const AName: UTF8String; ADefault: integer = 0): integer; virtual;
    // Read the subnode with AName and return its UTF8String value. If the subnode is
    // not found, ADefault will be returned.
    function ReadString(const AName: UTF8String; const ADefault: UTF8String = ''): UTF8String; virtual;
    // Read the subnode with AName and return its UnicodeString value. If the subnode is
    // not found, ADefault will be returned.
    function ReadUnicodeString(const AName: UTF8String; const ADefault: UnicodeString = ''): UnicodeString; virtual;
    // Sort the child nodes of this node. Provide a custom node compare function in Compare,
    // or attach an event handler to the parent documents' OnNodeCompare in order to
    // provide custom sorting. If no compare function is given (nil) and OnNodeCompare
    // is not implemented, SortChildNodes will simply sort the nodes by name (ascending,
    // case insensitive). The Info pointer parameter can be used to pass any custom
    // information to the compare function. Default value for Info is nil.
    procedure SortChildNodes(Compare: TXMLNodeCompareFunction = nil; Info: TPointer = nil);
    // Use ToUnicodeString to convert any UTF8 String from the node (name, value, attributes)
    // to a UnicodeString.
    function ToUnicodeString(const s: UTF8String): UnicodeString;
    // Convert the node's value to boolean and return the result. If this conversion
    // fails, or no value is found, then the function returns ADefault.
    function ValueAsBoolDef(ADefault: boolean): boolean; virtual;
    // Convert the node's value to a TDateTime and return the result. If this conversion
    // fails, or no value is found, then the function returns ADefault.
    function ValueAsDateTimeDef(ADefault: TDateTime): TDateTime; virtual;
    // Convert the node's value to a double and return the result. If this conversion
    // fails, or no value is found, then the function returns ADefault.
    function ValueAsFloatDef(ADefault: double): double; virtual;
    // Convert the node's value to int64 and return the result. If this conversion
    // fails, or no value is found, then the function returns ADefault.
    function ValueAsInt64Def(ADefault: int64): int64; virtual;
    // Convert the node's value to integer and return the result. If this conversion
    // fails, or no value is found, then the function returns ADefault.
    function ValueAsIntegerDef(ADefault: integer): integer; virtual;
    // If the attribute with name AName exists, then set its value to the boolean
    // AValue. If it does not exist, then create a new attribute AName with the
    // boolean value converted to either "True" or "False". If ADefault = AValue, and
    // WriteOnDefault = False, no attribute will be added.
    procedure WriteAttributeBool(const AName: UTF8String; AValue: boolean; ADefault: boolean = False); virtual;
    procedure WriteAttributeDateTime(const AName: UTF8string; AValue: TDateTime; ADefault: TDateTime = 0); virtual;
    // If the attribute with name AName exists, then set its value to the integer
    // AValue. If it does not exist, then create a new attribute AName with the
    // integer value converted to a quoted string. If ADefault = AValue, and
    // WriteOnDefault = False, no attribute will be added.
    procedure WriteAttributeInteger(const AName: UTF8String; AValue: integer; ADefault: integer = 0); virtual;
    procedure WriteAttributeInt64(const AName: UTF8String; const AValue: int64; ADefault: int64 = 0); virtual;
    procedure WriteAttributeFloat(const AName: UTF8String; AValue: double; ADefault: double = 0); virtual;
    // If the attribute with name AName exists, then set its value to the UTF8String
    // AValue. If it does not exist, then create a new attribute AName with the
    // value AValue. If ADefault = AValue, and WriteOnDefault = False, no attribute
    // will be added.
    procedure WriteAttributeString(const AName: UTF8String; const AValue: UTF8String; const ADefault: UTF8String = ''); virtual;
    // Add or replace the subnode with AName and set its value to represent the boolean
    // AValue. If AValue = ADefault, and WriteOnDefault = False, no subnode will be added.
    procedure WriteBool(const AName: UTF8String; AValue: boolean; ADefault: boolean = False); virtual;
    {$IFDEF USEGRAPHICS}
    // Write properties Color and Style of the TBrush object ABrush to the subnode
    // with AName. If AName does not exist, it will be created.
    procedure WriteBrush(const AName: UTF8String; ABrush: TBrush); virtual;
    // Add or replace the subnode with AName and set its value to represent the TColor
    // AValue. If AValue = ADefault, and WriteOnDefault = False, no subnode will be added.
    procedure WriteColor(const AName: UTF8String; AValue: TColor; ADefault: TColor = clBlack); virtual;
    // Write properties \Name, Color, Size and Style of the TFont object AFont to
    // the subnode with AName. If AName does not exist, it will be created.
    procedure WriteFont(const AName: UTF8String; AFont: TFont); virtual;
    // Write properties Color, Mode, Style and Width of the TPen object APen to
    // the subnode with AName. If AName does not exist, it will be created.
    procedure WritePen(const AName: UTF8String; APen: TPen); virtual;
    {$ENDIF}
    // Add or replace the subnode with AName and set its value to represent the TDateTime
    // AValue. If AValue = ADefault, and WriteOnDefault = False, no subnode will be added.
    // The XML format used is compliant with W3C's specification of date and time.
    procedure WriteDateTime(const AName: UTF8String; AValue: TDateTime; ADefault: TDateTime = 0); virtual;
    // Add or replace the subnode with AName and set its value to represent the double
    // AValue. If AValue = ADefault, and WriteOnDefault = False, no subnode will be added.
    procedure WriteFloat(const AName: UTF8String; AValue: double; ADefault: double = 0.0); virtual;
    // Add or replace the subnode with AName and set its value to represent the hexadecimal representation of
    // AValue. If AValue = ADefault, and WriteOnDefault = False, no subnode will be added.
    procedure WriteHex(const AName: UTF8String; AValue: integer; Digits: integer; ADefault: integer = 0); virtual;
    // Add or replace the subnode with AName and set its value to represent the int64
    // AValue. If AValue = ADefault, and WriteOnDefault = False, no subnode will be added.
    procedure WriteInt64(const AName: UTF8String; AValue: int64; ADefault: int64 = 0); virtual;
    // Add or replace the subnode with AName and set its value to represent the integer
    // AValue. If AValue = ADefault, and WriteOnDefault = False, no subnode will be added.
    procedure WriteInteger(const AName: UTF8String; AValue: integer; ADefault: integer = 0); virtual;
    // Add or replace the subnode with AName and set its value to represent the UTF8String
    // AValue. If AValue = ADefault, and WriteOnDefault = False, no subnode will be added.
    procedure WriteString(const AName, AValue: UTF8String; const ADefault: UTF8String = ''); virtual;
    // Call WriteToString to save the XML node to a UTF8String. This method can be used to store
    // individual nodes instead of the complete XML document.
    function WriteToString: UTF8String; virtual;
    // Add or replace the subnode with AName and set its value to represent the UnicodeString
    // AValue. If AValue = ADefault, and WriteOnDefault = False, no subnode will be added.
    procedure WriteUnicodeString(const AName: UTF8String; const AValue: UnicodeString; const ADefault: UnicodeString = ''); virtual;
    // AttributeByName returns the attribute value for the attribute that has name AName.
    // Set AttributeByName to add an attribute to the attribute list, or replace an
    // existing one.
    property AttributeByName[const AName: UTF8String]: UTF8String read GetAttributeByName write
      SetAttributeByName;
    // AttributeByNameWide returns the attribute value for the attribute that has name AName
    // as UnicodeString. Set AttributeByNameWide to add an attribute to the attribute list, or replace an
    // existing one.
    property AttributeByNameWide[const AName: UTF8String]: UnicodeString read GetAttributeByNameWide write
      SetAttributeByNameWide;
    // Returns the number of attributes in the current node.
    property AttributeCount: integer read GetAttributeCount;
    // Read this property to get the name of the attribute at Index. Note that Index
    // is zero-based: Index goes from 0 to AttributeCount - 1
    property AttributeName[Index: integer]: UTF8String read GetAttributeName write SetAttributeName;
    // Read this property to get the Attribute \Name and Value pair at index Index.
    // This is a UTF8String with \Name and Value separated by a TAB character (#9).
    property AttributePair[Index: integer]: UTF8String read GetAttributePair;
    // Read this property to get the UTF8String value of the attribute at index Index.
    // Write to it to set the UTF8String value.
    property AttributeValue[Index: integer]: UTF8String read GetAttributeValue write SetAttributeValue;
    // Read this property to get the UnicodeString value of the attribute at index Index.
    // Write to it to set the UnicodeString value.
    property AttributeValueAsUnicodeString[Index: integer]: UnicodeString read GetAttributeValueAsUnicodeString write SetAttributeValueAsUnicodeString;
    // Read this property to get the integer value of the attribute at index Index.
    // If the value cannot be converted, 0 will be returned. Write to it to set the integer value.
    property AttributeValueAsInteger[Index: integer]: integer read GetAttributeValueAsInteger write SetAttributeValueAsInteger;
    // Set or get the raw attribute value, thus circumventing the escape function. Make sure that
    // the value you set does not contain the & and quote AnsiCharacters, or the produced
    // XML will be invalid.
    property AttributeValueDirect[Index: integer]: UTF8String read GetAttributeValueDirect write SetAttributeValueDirect;
    // BinaryEncoding reflects the same value as the BinaryEncoding setting of the parent
    // Document.
    property BinaryEncoding: TBinaryEncodingType read GetBinaryEncoding write SetBinaryEncoding;
    // Use BinaryString to add/extract binary data in an easy way to/from the node. Internally the
    // data gets stored as Base64-encoded data. Do not use this method for normal textual
    // information, it is better to use ValueAsString in that case (adds less overhead).
    property BinaryString: RawByteString read GetBinaryString write SetBinaryString;
    // This property returns the name and index and all predecessors with underscores
    // to separate, in order to get a unique reference that can be used in filenames.
    property CascadedName: UTF8String read GetCascadedName;
    // Pointer to parent NativeXml document, or Nil if none.
    property Document: TNativeXml read FDocument write FDocument;
    // ElementType contains the type of element that this node holds.
    property ElementType: TXmlElementType read FElementType write FElementType;
    // Fullpath will return the complete path of the node from the root, e.g.
    // /Root/SubNode1/SubNode2/ThisNode
    property FullPath: UTF8String read GetFullPath;
    // Read Name to get the name of the element, and write Name to set the name.
    // This is the full name and may include a namespace. (Namespace:Name)
    property Name: UTF8String read FName write SetName;
    // Parent points to the parent node of the current XML node.
    property Parent: TXmlNode read FParent write FParent;
    // NodeCount is the number of child nodes that this node holds. In order to
    // loop through all child nodes, use a construct like this:
    // <CODE>
    // with MyNode do
    //   for i := 0 to NodeCount - 1 do
    //     with Nodes[i] do
    //     ..processing here
    // </CODE>
    property NodeCount: integer read GetNodeCount;
    // Use Nodes to access the child nodes of the current XML node by index. Note
    // that the list is zero-based, so Index is valid from 0 to NodeCount - 1.
    property Nodes[Index: integer]: TXmlNode read GetNodes; default;
    // Tag is an integer value the developer can use in any way. Tag does not get
    // saved to the XML. Tag is often used to point to a GUI element (and is then
    // cast to a pointer).
    property Tag: integer read FTag write FTag;
    // TotalNodeCount represents the total number of child nodes, and child nodes
    // of child nodes etcetera of this particular node. Use the following to get
    // the total number of nodes in the XML document:
    // <CODE>
    // Total := MyDoc.RootNodes.TotalNodeCount;
    // </CODE>
    property TotalNodeCount: integer read GetTotalNodeCount;
    // Read TreeDepth to find out many nested levels there are for the current XML
    // node. Root has a TreeDepth of zero.
    property TreeDepth: integer read GetTreeDepth;
    // ValueAsBool returns the node's value as boolean, or raises an
    // exception if the value cannot be converted to boolean. Set ValueAsBool
    // to convert a boolean to a UTF8String in the node's value field. See also
    // function ValueAsBoolDef.
    property ValueAsBool: boolean read GetValueAsBool write SetValueAsBool;
    // ValueAsDateTime returns the node's value as TDateTime, or raises an
    // exception if the value cannot be converted to TDateTime. Set ValueAsDateTime
    // to convert a TDateTime to a UTF8String in the node's value field. See also
    // function ValueAsDateTimeDef.
    property ValueAsDateTime: TDateTime read GetValueAsDateTime write SetValueAsDateTime;
    // ValueAsIn64 returns the node's value as int64, or raises an
    // exception if the value cannot be converted to int64. Set ValueAsInt64
    // to convert an int64 to a UTF8String in the node's value field. See also
    // function ValueAsInt64Def.
    property ValueAsInt64: int64 read GetValueAsInt64 write SetValueAsInt64;
    // ValueAsInteger returns the node's value as integer, or raises an
    // exception if the value cannot be converted to integer. Set ValueAsInteger
    // to convert an integer to a UTF8String in the node's value field. See also
    // function ValueAsIntegerDef.
    property ValueAsInteger: integer read GetValueAsInteger write SetValueAsInteger;
    // ValueAsFloat returns the node's value as float, or raises an
    // exception if the value cannot be converted to float. Set ValueAsFloat
    // to convert a float to a UTF8String in the node's value field. See also
    // function ValueAsFloatDef.
    property ValueAsFloat: double read GetValueAsFloat write SetValueAsFloat;
    // ValueAsString returns the unescaped version of ValueDirect. All neccesary
    // characters in ValueDirect must be escaped (e.g. "&" becomes "&amp;") but
    // ValueAsString returns them in original format. Always use ValueAsString to
    // set the text value of a node, to make sure all neccesary charaters are
    // escaped.
    property ValueAsString: UTF8String read GetValueAsString write SetValueAsString;
    // ValueAsUnicodeString returns the unescaped version of ValueDirect as a UnicodeString.
    // Always use ValueAsUnicodeString to set the text value of a node, to make sure all
    // neccesary charaters are escaped.
    property ValueAsUnicodeString: UnicodeString read GetValueAsUnicodeString write SetValueAsUnicodeString;
    // ValueDirect is the exact text value as was parsed from the stream. If multiple
    // text elements are encountered, they are added to ValueDirect with a CR to
    // separate them.
    property ValueDirect: UTF8String read FValue write FValue;
    // WriteOnDefault reflects the same value as the WriteOnDefault setting of the parent
    // Document.
    property WriteOnDefault: boolean read GetWriteOnDefault;
  end;

  // TXmlNodeList is a utility TList descendant that can be used to work with selection
  // lists. An example:
  // <code>
  // procedure FindAllZips(ANode: TXmlNode);
  // var
  //   i: integer;
  //   AList: TXmlNodeList;
  // begin
  //   AList := TXmlNodeList.Create;
  //   try
  //     // Get a list of all nodes named 'ZIP'
  //     ANode.NodesByName('ZIP', AList);
  //     for i := 0 to AList.Count - 1 do
  //       // Write the value of the node to output. Since AList[i] will be
  //       // of type TXmlNode, we can directly access the Value property.
  //       WriteLn(AList[i].Value);
  //   finally
  //     AList.Free;
  //   end;
  // end;
  // </code>
  TXmlNodeList = class(TList)
  private
    function GetItems(Index: Integer): TXmlNode;
    procedure SetItems(Index: Integer; const Value: TXmlNode);
  public
    // Return the first node in the list that has an attribute with AName, AValue
    function ByAttribute(const AName, AValue: UTF8String): TXmlNode;
    property Items[Index: Integer]: TXmlNode read GetItems write SetItems; default;
  end;

  // TNativeXml is the XML document holder. Create a TNativeXml and then use
  // methods LoadFromFile, LoadFromStream or ReadFromString to load an XML document
  // into memory. Or start from scratch and use Root.NodeNew to add nodes and
  // eventually SaveToFile and SaveToStream to save the results as an XML document.
  // Use property Xmlformat = xfReadable to ensure that indented (readable) output
  // is produced.
  TNativeXml = class(TPersistent)
  private
    FAbortParsing: boolean;         // Signal to abort the parsing process
    FBinaryEncoding: TBinaryEncodingType; // xbeBinHex or xbeBase64
    FCodecStream: TsdCodecStream;   // Temporary stream used to read encoded files
    FDropCommentsOnParse: boolean;  // If true, comments are dropped (deleted) when parsing
    FExternalEncoding: TStringEncodingType;
    FFloatAllowScientific: boolean;
    FFloatSignificantDigits: integer;
    FParserWarnings: boolean;       // Show parser warnings for non-critical errors
    FRootNodes: TXmlNode;           // Root nodes in the document (which contains one normal element that is the root)
    FIndentString: UTF8String;      // The indent string used to indent content (default is two spaces)
    FUseFullNodes: boolean;         // If true, nodes are never written in short notation.
    FUseLocalBias: Boolean;         // If true, datetime values are written with timezone offset and converted to local time when read
    FWriteOnDefault: boolean;       // Set this option to "False" to only write values <> default value (default = true)
    FXmlFormat: TXmlFormatType;     // xfReadable, xfCompact
    FOnNodeCompare: TXmlNodeCompareEvent; // Compare two nodes
    FOnNodeNew: TXmlNodeEvent;      // Called after a node is added
    FOnNodeLoaded: TXmlNodeEvent;   // Called after a node is loaded completely
    FOnProgress: TXmlProgressEvent; // Called after a node is loaded/saved, with the current position in the file
    FOnUnicodeLoss: TNotifyEvent;   // This event is called when there is a warning for unicode conversion loss when reading unicode
    procedure DoNodeNew(Node: TXmlNode);
    procedure DoNodeLoaded(Node: TXmlNode);
    procedure DoUnicodeLoss(Sender: TObject);
    function GetCommentString: UTF8String;
    procedure SetCommentString(const Value: UTF8String);
    function GetEntityByName(AName: UTF8String): UTF8String;
    function GetRoot: TXmlNode;
    function GetEncodingString: UTF8String;
    procedure SetEncodingString(const Value: UTF8String);
    function GetVersionString: UTF8String;
    procedure SetVersionString(const Value: UTF8String);
    function GetStyleSheetNode: TXmlNode;
    function GetUtf8Encoded: boolean;
  protected
    procedure CopyFrom(Source: TNativeXml); virtual;
    procedure DoProgress(Size: integer);
    function LineFeed: UTF8String; virtual;
    procedure ParseDTD(ANode: TXmlNode; S: TStream); virtual;
    procedure ReadFromStream(S: TStream); virtual;
    procedure WriteToStream(S: TStream); virtual;
    procedure SetDefaults; virtual;
  public
    // Create a new NativeXml document which can then be used to read or write XML files.
    // A document that is created with Create must later be freed using Free.
    // Example:
    // <Code>
    // var
    //   ADoc: TNativeXml;
    // begin
    //   ADoc := TNativeXml.Create;
    //   try
    //     ADoc.LoadFromFile('c:\\temp\\myxml.xml');
    //     {do something with the document here}
    //   finally
    //     ADoc.Free;
    //   end;
    // end;
    // </Code>
    constructor Create; virtual;
    // Use CreateName to Create a new Xml document that will automatically
    // contain a root element with name ARootName.
    constructor CreateName(const ARootName: UTF8String); virtual;
    // Destroy will free all data in the TNativeXml object. This includes the
    // root node and all subnodes under it. Do not call Destroy directly, call
    // Free instead.
    destructor Destroy; override;
    // When calling Assign with a Source object that is a TNativeXml, will cause
    // it to copy all data from Source.
    procedure Assign(Source: TPersistent); override;
    // Call Clear to remove all data from the object, and restore all defaults.
    procedure Clear; virtual;
    // Function IsEmpty returns true if the root is clear, or in other words, the
    // root contains no value, no name, no subnodes and no attributes.
    function IsEmpty: boolean; virtual;
    // Load an XML document from the TStream object in Stream. The LoadFromStream
    // procedure will raise an exception of type EFilerError when it encounters
    // non-wellformed XML. This method can be used with any TStream descendant.
    // See also LoadFromFile and ReadFromString.
    procedure LoadFromStream(Stream: TStream); virtual;
    // Call procedure LoadFromFile to load an XML document from the filename
    // specified. See Create for an example. The LoadFromFile procedure will raise
    // an exception of type EFilerError when it encounters non-wellformed XML.
    procedure LoadFromFile(const AFileName: string); virtual;
    // Call procedure ReadFromString to load an XML document from the UTF8String AValue.
    // The ReadFromString procedure will raise an exception of type EFilerError
    // when it encounters non-wellformed XML.
    procedure ReadFromString(const AValue: UTF8String); virtual;
    // Call ResolveEntityReferences after the document has been loaded to resolve
    // any present entity references (&Entity;). When an entity is found in the
    // DTD, it will replace the entity reference. Whenever an entity contains
    // XML markup, it will be parsed and become part of the document tree. Since
    // calling ResolveEntityReferences is adding quite some extra overhead, it
    // is not done automatically. If you want to do the entity replacement, a good
    // moment to call ResolveEntityReferences is right after LoadFromFile.
    procedure ResolveEntityReferences;
    // Call SaveToStream to save the XML document to the Stream. Stream
    // can be any TStream descendant. Set XmlFormat to xfReadable if you want
    // the stream to contain indentations to make the XML more human-readable. This
    // is not the default and also not compliant with the XML specification. See
    // SaveToFile for information on how to save in special encoding.
    procedure SaveToStream(Stream: TStream); virtual;
    // Call SaveToFile to save the XML document to a file with FileName. If the
    // filename exists, it will be overwritten without warning. If the file cannot
    // be created, a standard I/O exception will be generated. Set XmlFormat to
    // xfReadable if you want the file to contain indentations to make the XML
    // more human-readable. This is not the default and also not compliant with
    // the XML specification.<p>
    // Saving to special encoding types can be achieved by setting two properties
    // before saving:
    // * ExternalEncoding
    // * EncodingString
    // ExternalEncoding can be se8bit (for plain ascii), seUtf8 (UTF-8), seUtf16LE
    // (for unicode) or seUtf16BE (unicode big endian).<p> Do not forget to also
    // set the EncodingString (e.g. "UTF-8" or "UTF-16") which matches with your
    // ExternalEncoding.
    procedure SaveToFile(const AFileName: string); virtual;
    // Call WriteToString to save the XML document to a UTF8String. Set XmlFormat to
    // xfReadable if you want the UTF8String to contain indentations to make the XML
    // more human-readable. This is not the default and also not compliant with
    // the XML specification.
    function WriteToString: UTF8String; virtual;
    // Set AbortParsing to True if you use the OnNodeNew and OnNodeLoaded events in
    // a SAX-like manner, and you want to abort the parsing process halfway. Example:
    // <code>
    // procedure MyForm.NativeXmlNodeLoaded(Sender: TObject; Node: TXmlNode);
    // begin
    //   if (Node.Name = 'LastNode') and (Sender is TNativeXml) then
    //     TNativeXml(Sender).AbortParsing := True;
    // end;
    // </code>
    property AbortParsing: boolean read FAbortParsing write FAbortParsing;
    // Choose what kind of binary encoding will be used when calling TXmlNode.BufferRead
    // and TXmlNode.BufferWrite. Default value is xbeBase64.
    property BinaryEncoding: TBinaryEncodingType read FBinaryEncoding write FBinaryEncoding;
    // A comment string above the root element \<!--{comment}--\> can be accessed with
    // this property. \Assign a comment to this property to add it to the XML document.
    // Use property RootNodeList to add/insert/extract multiple comments.
    property CommentString: UTF8String read GetCommentString write SetCommentString;
    // Set DropCommentsOnParse if you're not interested in any comment nodes in your object
    // model data. All comments encountered during parsing will simply be skipped and
    // not added as a node with ElementType = xeComment (which is default). Note that
    // when you set this option, you cannot later reconstruct an XML file with the comments
    // back in place.
    property DropCommentsOnParse: boolean read FDropCommentsOnParse write FDropCommentsOnParse;
    // Encoding string (e.g. "UTF-8" or "UTF-16"). This encoding string is stored in
    // the header.
    // Example: In order to get this header:
    // <?xml version="1.0" encoding="UTF-16" ?>
    // enter this code:
    // <CODE>MyXmlDocument.EncodingString := 'UTF-16';</CODE>
    // When reading a file, EncodingString will contain the encoding used.
    property EncodingString: UTF8String read GetEncodingString write SetEncodingString;
    // Returns the value of the named entity in Name, where name should be stripped
    // of the leading & and trailing ;. These entity values are parsed from the
    // Doctype declaration (if any).
    property EntityByName[AName: UTF8String]: UTF8String read GetEntityByName;
    // ExternalEncoding defines in which format XML files are saved. Set ExternalEncoding
    // to se8bit to save as plain text files, to seUtf8 to save as UTF8 files (with
    // Byte Order Mark #EF BB FF) and to seUTF16LE to save as unicode (Byte Order
    // Mark #FF FE). When reading an XML file, the value of ExternalEncoding will
    // be set according to the byte order mark and/or encoding declaration found.
    property ExternalEncoding: TStringEncodingType read FExternalEncoding write FExternalEncoding;
    // When converting floating point values to strings (e.g. in WriteFloat),
    // NativeXml will allow to output scientific notation in some cases, if the
    // result is significantly shorter than normal output, but only if the value
    // of FloatAllowScientific is True (default).
    property FloatAllowScientific: boolean read FFloatAllowScientific write FFloatAllowScientific;
    // When converting floating point values to strings (e.g. in WriteFloat),
    // NativeXml will use this number of significant digits. The default is
    // cDefaultFloatSignificantDigits, and set to 6.
    property FloatSignificantDigits: integer read FFloatSignificantDigits write FFloatSignificantDigits;
    // IndentString is the string used for indentations. By default, it is two
    // spaces: '  '. Set IndentString to something else if you need to have
    // specific indentation, or set it to an empty string to avoid indentation.
    property IndentString: UTF8String read FIndentString write FIndentString;
    // Root is the topmost element in the XML document. Access Root to read any
    // child elements. When creating a new XML document, you can automatically
    // include a Root node, by creating using CreateName.
    property Root: TXmlNode read GetRoot;
    // RootNodeList can be used to directly access the nodes in the root of the
    // XML document. Usually this list consists of one declaration node followed
    // by a normal node which is the Root. You can use this property to add or
    // delete comments, stylesheets, dtd's etc.
    property RootNodeList: TXmlNode read FRootNodes;
    // Get the stylesheet node used for this XML document. If the node does not
    // exist yet, it will be created (thus if you use this property, and don't
    // set any of the attributes, an empty stylesheet node will be the result).
    property StyleSheetNode: TXmlNode read GetStyleSheetNode;
    // Set UseFullNodes to True before saving the XML document to ensure that all
    // nodes are represented by <Node>...</Node> instead of the short version
    // <Node/>. UseFullNodes is False by default.
    property UseFullNodes: boolean read FUseFullNodes write FUseFullNodes;
    // Set UseLocalBias to True if you want to consider the local timezone bias
    // when writing and reading datetime values. UseLocalBias is False by default.
    property UseLocalBias: Boolean read FUseLocalBias write FUseLocalBias;
    // This property is here for backwards compat: all strings inside NativeXml
    // are UTF8Strings, the internal encoding is always UTF8.
    property Utf8Encoded: boolean read GetUtf8Encoded;
    // After reading, this property contains the XML version (usually "1.0").
    property VersionString: UTF8String read GetVersionString write SetVersionString;
    // Set WriteOnDefault to False if you do not want to write default values to
    // the XML document. This option can avoid creating huge documents with
    // redundant info, and will speed up writing.
    property WriteOnDefault: boolean read FWriteOnDefault write FWriteOnDefault;
    // XmlFormat by default is set to xfCompact. This setting is compliant to the spec,
    // and NativeXml will only generate XML files with #$0A as control AnsiCharacter.
    // By setting XmlFormat to xfReadable, you can generate easily readable XML
    // files that contain indentation and carriage returns after each element.
    property XmlFormat: TXmlFormatType read FXmlFormat write FXmlFormat;
    // ParserWarnings by default is True. If True, the parser will raise an
    // exception in cases where the XML document is not technically valid. If False,
    // the parser will try to ignore non-critical warnings. Set ParserWarnings
    // to False for some types of XML-based documents such as SOAP messages.
    property ParserWarnings: boolean read FParserWarnings write FParserWarnings;
    // This event is called whenever a node's SortChildNodes method is called and
    // no direct compare method is provided. Implement this event if you want to
    // use object-event based methods for comparison of nodes.
    property OnNodeCompare: TXmlNodeCompareEvent read FOnNodeCompare write FOnNodeCompare;
    // This event is called whenever the parser has encountered a new node.
    property OnNodeNew: TXmlNodeEvent read FOnNodeNew write FOnNodeNew;
    // This event is called when the parser has finished parsing the node, and
    // has created its complete contents in memory.
    property OnNodeLoaded: TXmlNodeEvent read FOnNodeLoaded write FOnNodeLoaded;
    // OnProgress is called during loading and saving of the XML document. The
    // Size parameter contains the position in the stream. This event can be used
    // to implement a progress indicator during loading and saving. The event is
    // called after each node that is read or written.
    property OnProgress: TXmlProgressEvent read FOnProgress write FOnProgress;
    // This event is called if there is a warning for unicode conversion loss,
    // when reading from Unicode streams or files.
    property OnUnicodeLoss: TNotifyEvent read FOnUnicodeLoss write FOnUnicodeLoss;
  end;

  // This enumeration defines the conversion stream access mode.
  TsdStreamModeType = (
    umUnknown, // The stream access mode is not yet known
    umRead,    // UTF stream opened for reading
    umWrite    // UTF stream opened for writing
  );

  // TBigByteArray is an array of bytes like the standard TByteArray (windows
  // unit) but which can contain up to MaxInt bytes. This type helps avoiding
  // range check errors when working with buffers larger than 32768 bytes.
  TBigByteArray = array[0..MaxInt - 1] of byte;
  PBigByteArray = ^TBigByteArray;

{$IFDEF CLR}

  // not implemented
  TsdBufferedStream = class(TStream)
  private
    FStream: TStream;
    FOwned: Boolean;
  protected
    procedure SetSize(NewSize: Int64); override;
  public
    constructor Create(AStream: TStream; Owned: Boolean = False);
    destructor Destroy; override;
    function Read(var Buffer: array of Byte; Offset, Count: Longint): Longint; override;
    function Write(const Buffer: array of Byte; Offset, Count: Longint): Longint; override;
    function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override;
  end;

  TsdBufferedReadStream = TsdBufferedStream;

  TsdBufferedWriteStream = TsdBufferedStream;

{$ELSE}

  // TsdBufferedReadStream is a buffered stream that takes another TStream
  // and reads only buffer-wise from it, and reads to the stream are first
  // done from the buffer. This stream type can only support reading.
  TsdBufferedReadStream = class(TStream)
  private
    FStream: TStream;
    FBuffer: PBigByteArray;
    FPage: integer;
    FBufPos: integer;
    FBufSize: integer;
    FPosition: longint;
    FOwned: boolean;
    FMustCheck: boolean;
  protected
    procedure CheckPosition;
  public
    // Create the buffered reader stream by passing the source stream in AStream,
    // this source stream must already be initialized. If Owned is set to True,
    // the source stream will be freed by TsdBufferedReadStream.
    constructor Create(AStream: TStream; Owned: boolean = False);
    destructor Destroy; override;
    function Read(var Buffer; Count: Longint): Longint; override;
    function Write(const Buffer; Count: Longint): Longint; override;
    function Seek(Offset: Longint; Origin: Word): Longint; override;
  end;

  // TsdBufferedWriteStream is a buffered stream that takes another TStream
  // and writes only buffer-wise to it, and writes to the stream are first
  // done to the buffer. This stream type can only support writing.
  TsdBufferedWriteStream = class(TStream)
  private
    FStream: TStream;
    FBuffer: PBigByteArray;
    FBufPos: integer;
    FPosition: longint;
    FOwned: boolean;
  protected
    procedure Flush;
  public
    // Create the buffered writer stream by passing the destination stream in AStream,
    // this destination stream must already be initialized. If Owned is set to True,
    // the destination stream will be freed by TsdBufferedWriteStream.
    constructor Create(AStream: TStream; Owned: boolean = False);
    destructor Destroy; override;
    function Read(var Buffer; Count: Longint): Longint; override;
    function Write(const Buffer; Count: Longint): Longint; override;
    function Seek(Offset: Longint; Origin: Word): Longint; override;
  end;

{$ENDIF}

  // TsdCodecStream is the base codec class for reading and writing encoded files.
  // See TsdUtf8Stream for more information.
  TsdCodecStream = class(TStream)
  private
    FBuffer: UTF8String;            // Buffer that holds temporary utf8 characters
    FBufferPos: integer;            // Current character in buffer
    FEncoding: TStringEncodingType; // Type of string encoding used for the external stream
    FMode: TsdStreamModeType;       // Access mode of this UTF stream, determined after first read/write
    FPosMin1: integer;              // Position for seek(-1)
    FPosMin2: integer;              // Position for seek(-2)
    FStream: TStream;               // Referenced stream
    FSwapByteOrder: boolean;
    FWarningUnicodeLoss: boolean;   // There was a warning for a unicode conversion loss
    FWriteBom: boolean;
    FOnUnicodeLoss: TNotifyEvent;   // This event is called if there is a warning for unicode conversion loss
  protected
    function ReadByte: byte; virtual;
    procedure StorePrevPositions; virtual;
    procedure WriteByte(const B: byte); virtual;
    procedure WriteBuf(const Buffer{$IFDEF CLR}: TBytes{$ENDIF}; Offset, Count: longint); virtual;
    function InternalRead(var Buffer{$IFDEF CLR}: array of Byte{$ENDIF}; Offset, Count: Longint): Longint;
    function InternalSeek(Offset: Longint; Origin: TSeekOrigin): Longint;
    function InternalWrite(const Buffer{$IFDEF CLR}: array of Byte{$ENDIF}; Offset, Count: Longint): Longint;
    {$IFDEF CLR}
    procedure SetSize(NewSize: Int64); override;
    {$ENDIF}
  public
    // Call Create to create a new TsdCodectream based on an input or output stream
    // in AStream. After the first Read, the input streamtype will be determined,
    // and the Encoding property will be set accordingly. When using Write to
    // write data to the referenced stream, the Encoding property must be set prior
    // to this, indicating what kind of stream to produce.
    constructor Create(AStream: TStream); virtual;
    // Read Count bytes from the referenced stream, and put them in Buffer. The function
    // returns the actual number of bytes read. The codec stream can only read
    // one byte at the time!
    {$IFDEF CLR}
    function Read(var Buffer: array of Byte; Offset, Count: Longint): Longint; override;
    {$ELSE}
    function Read(var Buffer; Count: Longint): Longint; override;
    {$ENDIF}
    // Seek to a new position in the stream, with Origin as a reference. The codec
    // stream can not seek when writing, and when reading can only go back one
    // AnsiCharacter, or return a position. Position returned is the position
    // in the referenced stream.
    {$IFDEF CLR}
    function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override;
    {$ELSE}
    function Seek(Offset: Longint; Origin: Word): Longint; override;
    {$ENDIF}
    // Write Count bytes from Buffer to the referenced stream, The function
    // returns the actual number of bytes written.
    {$IFDEF CLR}
    function Write(const Buffer: array of Byte; Offset, Count: Longint): Longint; override;
    {$ELSE}
    function Write(const Buffer; Count: Longint): Longint; override;
    {$ENDIF}
    // Set Encoding when writing to the preferred encoding of the output stream,
    // or read Encoding after reading the output stream to determine encoding type.
    property Encoding: TstringEncodingType read FEncoding write FEncoding;
    // \Read this value after loading an XML file. It will be True if there was a
    // warning for a unicode conversion loss.
    property WarningUnicodeLoss: boolean read FWarningUnicodeLoss;
    // This event is called if there is a warning for unicode conversion loss.
    property OnUnicodeLoss: TNotifyEvent read FOnUnicodeLoss write FOnUnicodeLoss;
  end;

  // TsdUdf8tream is a conversion stream that will load ANSI, UTF8 or
  // Unicode files and convert them into UTF8 only. The stream can
  // also save UTF8 data as Ansi, UTF8 or Unicode.
  TsdUtf8Stream = class(TsdCodecStream)
  private
  protected
    function ReadByte: byte; override;
    procedure WriteByte(const B: byte); override;
    procedure WriteBuf(const Buffer{$IFDEF CLR}: TBytes{$ENDIF}; Offset, Count: longint); override;
  end;

  // TsdSurplusReader is a simple class that can store a few surplus characters
  // and returns these first before reading from the underlying stream
  TsdSurplusReader = class
  private
    FStream: TStream;
    FSurplus: UTF8String;
  public
    constructor Create(AStream: TStream);
    property Surplus: UTF8String read FSurplus write FSurplus;
    function ReadChar(var Ch: AnsiChar): integer;
    function ReadCharSkipBlanks(var Ch: AnsiChar): boolean;
  end;

  // Simple string builder class that allocates string memory more effectively
  // to avoid repeated re-allocation
  TsdStringBuilder = class
  private
    FData: UTF8String;
    FCurrentIdx: integer;
    function GetData(Index: integer): AnsiChar;
    procedure Reallocate(RequiredLength: integer);
  public
    constructor Create;
    procedure Clear;
    procedure AddChar(Ch: AnsiChar);
    procedure AddString(var S: UTF8String);
    function StringCopy(AFirst, ALength: integer): UTF8String;
    function Value: UTF8String;
    property Length: integer read FCurrentIdx;
    property Data[Index: integer]: AnsiChar read GetData; default;
  end;

// String functions

function sdUTF8StringReplace(const S, OldPattern, NewPattern: UTF8String): UTF8String;

// Escape all required characters in string AValue.
function sdUTF8EscapeString(const AValue: UTF8String): UTF8String;

// Replace all escaped characters in string AValue by their original. This includes
// character references using &#...; and &#x...;
function sdUTF8UnEscapeString(const AValue: UTF8String): UTF8String;

// Enclose the string AValue in quotes.
function sdUTF8QuotedString(const AValue: UTF8String): UTF8String;

// Remove the quotes from string AValue.
function sdUTF8UnQuotedString(const AValue: UTF8String): UTF8String;

// This function adds control characters Chars repeatedly after each Interval
// of characters to UTF8String Value.
function sdAddControlChars(const AValue: UTF8String; const Chars: UTF8String; Interval: integer): UTF8String;

// This function removes control characters from UTF8String AValue (Tab, CR, LF and Space)
function sdRemoveControlChars(const AValue: UTF8String): UTF8String;

// Convert the UTF8String ADate to a TDateTime according to the W3C date/time specification
// as found here: http://www.w3.org/TR/NOTE-datetime
// If there is a conversion error, an exception will be raised.
function sdDateTimeFromString(const ADate: UTF8String; UseLocalBias: Boolean = False): TDateTime;

// Convert the UTF8String ADate to a TDateTime according to the W3C date/time specification
// as found here: http://www.w3.org/TR/NOTE-datetime
// If there is a conversion error, the default value ADefault is returned.
function sdDateTimeFromStringDefault(const ADate: UTF8String; ADefault: TDateTime;
  UseLocalBias: Boolean = False): TDateTime;

// Convert the TDateTime ADate to a UTF8String according to the W3C date/time specification
// as found here: http://www.w3.org/TR/NOTE-datetime
function sdDateTimeToString(ADate: TDateTime; UseLocalBias: Boolean = False): UTF8String;

// Convert a number to a UTF8String, using SignificantDigits to indicate the number of
// significant digits, and AllowScientific to allow for scientific notation if that
// results in much shorter notatoin.
function sdWriteNumber(Value: double; SignificantDigits: integer; AllowScientific: boolean): UTF8String;

// Write an UTF8String to the stream
procedure sdUTF8WriteStringToStream(S: TStream; const AString: UTF8String);

// Turn Ch to an UpCase character ('a'..'z' becomes 'A'..'Z')
function sdUpCase(Ch: AnsiChar): AnsiChar;

// Conversion between Ansi, UTF8 and Unicode

// Convert a UnicodeString to a UTF8 encoded string
function sdUnicodeToUtf8(const W: UnicodeString): UTF8String;

// Convert a AnsiString to a UTF8 encoded string
function sdAnsiToUtf8(const S: AnsiString): UTF8String;

// Convert a UTF8 encoded string to a UnicodeString
function sdUtf8ToUnicode(const S: UTF8String): UnicodeString;

// Convert a UTF8 encoded string to a AnsiString. This might cause loss!
function sdUtf8ToAnsi(const S: UTF8String): AnsiString;


// parse functions

// Find SubString within UTF8String S, only process characters between Start and Close.
// First occurrance is reported in APos. If something is found, function returns True.
function sdUTF8FindString(const SubString, S: UTF8String; Start, Close: integer; var APos: integer): boolean;

// Detect if the SubString matches the characters in S from position Start. S may be
// actually longer than SubString, only length(SubString) characters are checked.
function sdUTF8MatchString(const SubString: UTF8String; const S: UTF8String; Start: integer): boolean;

// Find all Name="Value" pairs in UTF8String AValue (from Start to Close - 1), and put
// the resulting attributes in stringlist Attributes. This stringlist must already
// be initialized when calling this function.
procedure sdUTF8ParseAttributes(const AValue: UTF8String; Start, Close: integer; Attributes: TsdUTF8StringList);

// Trim the UTF8String AValue between Start and Close - 1 (remove whitespaces at start
// and end), not by adapting the UTF8String but by adjusting the Start and Close indices.
// If the resulting UTF8String still has a length > 0, the function returns True.
function sdUTF8TrimPos(const AValue: UTF8String; var Start, Close: integer): boolean;

// Trim the UTF8String
function sdUTF8Trim(const AValue: UTF8String): UTF8String;

// Encoding/Decoding functions

// Encode binary data in Source as BASE64. The function returns the BASE64 encoded
// data as UTF8String, without any linebreaks.
function EncodeBase64(const Source: RawByteString): UTF8String;

// Decode BASE64 data in Source into binary data. The function returns the binary
// data as UTF8String. Use a TStringStream to convert this data to a stream. The Source
// UTF8String may contain linebreaks and control characters, these will be stripped.
function DecodeBase64(const Source: UTF8String): RawByteString;

// Encode binary data in Source as BINHEX. The function returns the BINHEX encoded
// data as UTF8String, without any linebreaks.
function EncodeBinHex(const Source: RawByteString): UTF8String;

// Decode BINHEX data in Source into binary data. The function returns the binary
// data as UTF8String. Use a TStringStream to convert this data to a stream. The Source
// UTF8String may contain linebreaks and control characters, these will be stripped.
function DecodeBinHex(const Source: UTF8String): RawByteString;

resourcestring

  sxeErrorUnexpectedChar         = 'Illegal character; expected "%s"';
  sxeErrorCalcStreamLength       = 'Error while calculating streamlength';
  sxeMissingDataInBinaryStream   = 'Missing data in binary stream';
  sxeMissingElementName          = 'Missing element name';
  sxeMissingCloseTag             = 'Missing close tag in element %s';
  sxeMissingDataAfterGreaterThan = 'Missing data after "<" in element %s';
  sxeMissingLessThanInCloseTag   = 'Missing ">" in close tag of element %s';
  sxeIncorrectCloseTag           = 'Incorrect close tag in element %s';
  sxeIllegalCharInNodeName       = 'Illegal character in node name "%s"';
  sxeMoreThanOneRootElement      = 'More than one root element found in xml';
  sxeMoreThanOneDeclaration      = 'More than one xml declaration found in xml';
  sxeDeclarationMustBeFirstElem  = 'Xml declaration must be first element';
  sxeMoreThanOneDoctype          = 'More than one doctype declaration found in root';
  sxeDoctypeAfterRootElement     = 'Doctype declaration found after root element';
  sxeNoRootElement               = 'No root element found in xml';
  sxeIllegalElementType          = 'Illegal element type';
  sxeCDATAInRoot                 = 'No CDATA allowed in root';
  sxeRootElementNotDefined       = 'XML root element not defined.';
  sxeCodecStreamNotAssigned      = 'Encoding stream unassigned';
  sxeUnsupportedEncoding         = 'Unsupported string encoding';
  sxeCannotReadCodecForWriting   = 'Cannot read from a conversion stream opened for writing';
  sxeCannotWriteCodecForReading  = 'Cannot write to an UTF stream opened for reading';
  sxeCannotReadMultipeChar       = 'Cannot read multiple chars from conversion stream at once';
  sxeCannotPerformSeek           = 'Cannot perform seek on codec stream';
  sxeCannotSeekBeforeReadWrite   = 'Cannot seek before reading or writing in conversion stream';
  sxeCannotSeek                  = 'Cannot perform seek in conversion stream';
  sxeCannotWriteToOutputStream   = 'Cannot write to output stream';
  sxeXmlNodeNotAssigned          = 'XML Node is not assigned';
  sxeCannotConverToBool          = 'Cannot convert value to bool';
  sxeCannotConvertToFloat        = 'Cannot convert value to float';
  sxeSignificantDigitsOutOfRange = 'Significant digits out of range';

implementation

uses
  System.UITypes, System.AnsiStrings;

type

  // Internal type
  TTagType = record
    Start: UTF8String;
    Close: UTF8String;
    Style: TXmlElementType;
  end;
  PByte = ^byte;

  TBomInfo = packed record
    BOM: array[0..3] of byte;
    Len: integer;
    Encoding: TStringEncodingType;
    HasBOM: boolean;
  end;

const

  // Count of different escape characters
  cEscapeCount = 5;

  // These are characters that must be escaped. Note that "&" is first since
  // when another would be replaced first (eg ">" by "&lt;") this could
  // cause the new "&" in "&lt;" to be replaced by "&amp;";
  cEscapes: array[0..cEscapeCount - 1] of UTF8String =
    ('&', '<', '>', '''', '"');

  // These are the strings that replace the escape strings - in the same order
  cReplaces: array[0..cEscapeCount - 1] of UTF8String =
    ('&amp;', '&lt;', '&gt;', '&apos;', '&quot;');

  cQuoteChars: set of AnsiChar = ['"', ''''];
  cControlChars: set of AnsiChar = [#9, #10, #13, #32]; {Tab, LF, CR, Space}

  // Count of different XML tags
  cTagCount = 12;

  cTags: array[0..cTagCount - 1] of TTagType = (
    // The order is important here; the items are searched for in appearing order
    (Start: '<![CDATA[';        Close: ']]>'; Style: xeCData),
    (Start: '<!DOCTYPE';        Close: '>';   Style: xeDoctype),
    (Start: '<!ELEMENT';        Close: '>';   Style: xeElement),
    (Start: '<!ATTLIST';        Close: '>';   Style: xeAttList),
    (Start: '<!ENTITY';         Close: '>';   Style: xeEntity),
    (Start: '<!NOTATION';       Close: '>';   Style: xeNotation),
    (Start: '<?xml-stylesheet'; Close: '?>';  Style: xeStylesheet),
    (Start: '<?xml';            Close: '?>';  Style: xeDeclaration),
    (Start: '<!--';             Close: '-->'; Style: xeComment),
    (Start: '<!';               Close: '>';   Style: xeExclam),
    (Start: '<?';               Close: '?>';  Style: xeQuestion),
    (Start: '<';                Close: '>';   Style: xeNormal) );
    // direct tags are derived from Normal tags by checking for the />

  // These constant are used when generating hexchars from buffer data
  cHexChar:       array[0..15] of AnsiChar = '0123456789ABCDEF';
  cHexCharLoCase: array[0..15] of AnsiChar = '0123456789abcdef';

  // These AnsiCharacters are used when generating BASE64 AnsiChars from buffer data
  cBase64Char: array[0..63] of AnsiChar =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  cBase64PadChar: AnsiChar = '=';

  // The amount of bytes to allocate with each increase of the value buffer
  cNodeValueBuf = 2048;

  // byte order marks for strings
  // Unicode text files should contain $FFFE as first character to identify such a file clearly. Depending on the system
  // where the file was created on this appears either in big endian or little endian style.

  const cBomInfoCount = 15;
  const cBomInfo: array[0..cBomInfoCount - 1] of TBomInfo =
  ( (BOM: ($00,$00,$FE,$FF); Len: 4; Encoding: seUCS4BE;    HasBOM: true),
    (BOM: ($FF,$FE,$00,$00); Len: 4; Encoding: seUCS4LE;    HasBOM: true),
    (BOM: ($00,$00,$FF,$FE); Len: 4; Encoding: seUCS4_2143; HasBOM: true),
    (BOM: ($FE,$FF,$00,$00); Len: 4; Encoding: seUCS4_3412; HasBOM: true),
    (BOM: ($FE,$FF,$00,$00); Len: 2; Encoding: seUTF16BE;   HasBOM: true),
    (BOM: ($FF,$FE,$00,$00); Len: 2; Encoding: seUTF16LE;   HasBOM: true),
    (BOM: ($EF,$BB,$BF,$00); Len: 3; Encoding: seUTF8;      HasBOM: true),
    (BOM: ($00,$00,$00,$3C); Len: 4; Encoding: seUCS4BE;    HasBOM: false),
    (BOM: ($3C,$00,$00,$00); Len: 4; Encoding: seUCS4LE;    HasBOM: false),
    (BOM: ($00,$00,$3C,$00); Len: 4; Encoding: seUCS4_2143; HasBOM: false),
    (BOM: ($00,$3C,$00,$00); Len: 4; Encoding: seUCS4_3412; HasBOM: false),
    (BOM: ($00,$3C,$00,$3F); Len: 4; Encoding: seUTF16BE;   HasBOM: false),
    (BOM: ($3C,$00,$3F,$00); Len: 4; Encoding: seUTF16LE;   HasBOM: false),
    (BOM: ($3C,$3F,$78,$6D); Len: 4; Encoding: seAnsi;      HasBOM: false),
    (BOM: ($4C,$6F,$A7,$94); Len: 4; Encoding: seEBCDIC;    HasBOM: false)
  );

// .NET compatible stub for TBytes (array of byte) type
{$IFNDEF CLR}
type
  TBytes = TBigByteArray;
{$ENDIF}

function StrScan(const Str: PAnsiChar; Chr: AnsiChar): PAnsiChar;
begin
  Result := Str;
  while Result^ <> Chr do
  begin
    if Result^ = #0 then
    begin
      Result := nil;
      Exit;
    end;
    Inc(Result);
  end;
end;

function UTF8QuotedStr(const S: UTF8String; Quote: AnsiChar): UTF8String;
var
  P, Src, Dest: PAnsiChar;
  AddCount: Integer;
begin
  AddCount := 0;
  P := StrScan(PAnsiChar(S), Quote);
  while P <> nil do
  begin
    Inc(P);
    Inc(AddCount);
    P := StrScan(P, Quote);
  end;
  if AddCount = 0 then
  begin
    Result := UTF8String(Quote) + S + UTF8String(Quote);
    Exit;
  end;
  SetLength(Result, Length(S) + AddCount + 2);
  Dest := Pointer(Result);
  Dest^ := Quote;
  Inc(Dest);
  Src := Pointer(S);
  P := StrScan(Src, Quote);
  repeat
    Inc(P);
    Move(Src^, Dest^, P - Src);
    Inc(Dest, P - Src);
    Dest^ := Quote;
    Inc(Dest);
    Src := P;
    P := StrScan(Src, Quote);
  until P = nil;
  P := System.AnsiStrings.StrEnd(Src);
  Move(Src^, Dest^, P - Src);
  Inc(Dest, P - Src);
  Dest^ := Quote;
end;

function UTF8ExtractQuotedStr(const S: UTF8String; Quote: AnsiChar): UTF8String;
var
  P, Src, Dest: PAnsiChar;
  DropCount: Integer;
begin
  Result := '';
  Src := PAnsiChar(S);
  if (Src = nil) or (Src^ <> Quote) then
    Exit;
  Inc(Src);
  DropCount := 1;
  P := Src;
  Src := StrScan(Src, Quote);
  while Src <> nil do
  begin
    Inc(Src);
    if Src^ <> Quote then
      Break;
    Inc(Src);
    Inc(DropCount);
    Src := StrScan(Src, Quote);
  end;
  if Src = nil then
    Src := System.AnsiStrings.StrEnd(P);
  if ((Src - P) <= 1) then
    Exit;
  if DropCount = 1 then
    SetString(Result, P, Src - P - 1)
  else
  begin
    SetLength(Result, Src - P - DropCount);
    Dest := PAnsiChar(Result);
    Src := StrScan(P, Quote);
    while Src <> nil do
    begin
      Inc(Src);
      if Src^ <> Quote then
        Break;
      Move(P^, Dest^, Src - P);
      Inc(Dest, Src - P);
      Inc(Src);
      P := Src;
      Src := StrScan(Src, Quote);
    end;
    if Src = nil then
      Src := System.AnsiStrings.StrEnd(P);
    Move(P^, Dest^, Src - P - 1);
  end;
end;

function Utf8Pos(const Substr, S: UTF8String): Integer;
var
  i, x: Integer;
  Len, LenSubStr: Integer;
begin
  i := 1;
  LenSubStr := Length(SubStr);
  Len := Length(S) - LenSubStr + 1;
  while i <= Len do
  begin
    if S[i] = SubStr[1] then
    begin
      x := 1;
      while (x < LenSubStr) and (S[i + x] = SubStr[x + 1]) do
        Inc(x);
      if (x = LenSubStr) then
      begin
        Result := i;
        exit;
      end;
    end;
    Inc(i);
  end;
  Result := 0;
end;

// .NET-compatible TStream.Write

function StreamWrite(Stream: TStream; const Buffer{$IFDEF CLR}: TBytes{$ENDIF}; Offset, Count: Longint): Longint;
begin
{$IFDEF CLR}
  Result := Stream.Write(Buffer, Offset, Count);
{$ELSE}
  Result := Stream.Write(TBytes(Buffer)[Offset], Count);
{$ENDIF}
end;

{$IFNDEF CLR}
// Delphi's implementation of TStringStream is severely flawed, it does a SetLength
// on each write, which slows down everything to a crawl. This implementation over-
// comes this issue.
type
  TsdUTF8StringStream = class(TMemoryStream)
  public
    constructor Create(const S: UTF8String);
    function DataString: UTF8String;
  end;

constructor TsdUTF8StringStream.Create(const S: UTF8String);
begin
  inherited Create;
  SetSize(length(S));
  if Size > 0 then
  begin
    Write(S[1], Size);
    Position := 0;
  end;
end;

function TsdUTF8StringStream.DataString: UTF8String;
begin
  SetLength(Result, Size);
  if Size > 0 then
  begin
    Position := 0;
    Read(Result[1], length(Result));
  end;
end;
{$ELSE}
// In .NET we use the standard TStringStream
type
  TsdUTF8StringStream = TStringStream;
{$ENDIF}

// Utility functions

function Min(A, B: integer): integer;
begin
  if A < B then
    Result := A
  else
    Result := B;
end;

function Max(A, B: integer): integer;
begin
  if A > B then
    Result := A
  else
    Result := B;
end;

function sdUTF8StringReplace(const S, OldPattern, NewPattern: UTF8String): UTF8String;
var
  SearchStr, NewStr: UTF8String;
  Offset: Integer;
begin
  // Case Sensitive, Replace All
  SearchStr := S;
  NewStr := S;
  Result := '';
  while SearchStr <> '' do
  begin
    Offset := UTF8Pos(OldPattern, SearchStr);
    if Offset = 0 then
    begin
      Result := Result + NewStr;
      Break;
    end;
    Result := Result + Copy(NewStr, 1, Offset - 1) + NewPattern;
    NewStr := Copy(NewStr, Offset + Length(OldPattern), MaxInt);
    SearchStr := Copy(SearchStr, Offset + Length(OldPattern), MaxInt);
  end;
end;

function sdUTF8EscapeString(const AValue: UTF8String): UTF8String;
var
  i: integer;
begin
  Result := AValue;
  for i := 0 to cEscapeCount - 1 do
    Result := sdUTF8StringReplace(Result, cEscapes[i], cReplaces[i]);
end;

function sdUTF8UnEscapeString(const AValue: UTF8String): UTF8String;
var
  SearchStr, Reference, Replace: UTF8String;
  i, Offset, Code: Integer;
  W: word;
begin
  SearchStr := AValue;
  Result := '';
  while SearchStr <> '' do
  begin
    // find '&'
    Offset := Utf8Pos('&', SearchStr);
    if Offset = 0 then
    begin
      // Nothing found
      Result := Result + SearchStr;
      Break;
    end;
    Result := Result + Copy(SearchStr, 1, Offset - 1);
    SearchStr := Copy(SearchStr, Offset, MaxInt);
    // find next ';'
    Offset := Utf8Pos(';', SearchStr);
    if Offset = 0 then
    begin
      // Error: encountered a '&' but not a ';'.. we will ignore, just return
      // the unmodified value
      Result := Result + SearchStr;
      Break;
    end;
    // Reference
    Reference := copy(SearchStr, 1, Offset);
    SearchStr := Copy(SearchStr, Offset + 1, MaxInt);
    Replace := Reference;
    // See if it is a Character reference
    if copy(Reference, 1, 2) = '&#' then
    begin
      Reference := copy(Reference, 3, length(Reference) - 3);
      if length(Reference) > 0 then
      begin
        if sdUpCase(Reference[1]) = 'X' then
          // Hex notation
          Reference[1] := '$';
        Code := StrToIntDef(string(Reference), -1);
        if (Code >= 0) and (Code < $FFFF) then
        begin
          W := Code;
          Replace := sdUnicodeToUtf8(UnicodeChar(W));
        end;
      end;
    end else
    begin
      // Look up default escapes
      for i := 0 to cEscapeCount - 1 do
        if Reference = cReplaces[i] then
        begin
          // Replace
          Replace := cEscapes[i];
          Break;
        end;
    end;
    // New result
    Result := Result + Replace;
  end;
end;

function sdUTF8QuotedString(const AValue: UTF8String): UTF8String;
var
  Quote: AnsiChar;
begin
  Quote := '"';
  if UTF8Pos('"', AValue) > 0 then
    Quote := '''';
{$IFDEF CLR}
  Result := QuotedStr(AValue, AQuoteChar);
{$ELSE}
  Result := UTF8QuotedStr(AValue, Quote);
{$ENDIF}
end;

function sdUTF8UnQuotedString(const AValue: UTF8String): UTF8String;
var
  Quote: AnsiChar;
begin
  if Length(AValue) < 2 then
  begin
    Result := AValue;
    exit;
  end;
  Quote := AValue[1];
  if Quote in cQuoteChars then
  begin
    {$IFDEF CLR}
    Result := DequotedStr(AValue, Quote);
    {$ELSE}
    Result := UTF8ExtractQuotedStr(AValue, Quote);
    {$ENDIF}
  end else
    Result := AValue;
end;

function sdAddControlChars(const AValue: UTF8String; const Chars: UTF8String; Interval: integer): UTF8String;
// Insert AnsiChars in AValue at each Interval AnsiChars
var
  i, j, ALength: integer;
  // local
  procedure InsertControlChars;
  var
    k: integer;
  begin
    for k := 1 to Length(Chars) do
    begin
      Result[j] := Chars[k];
      inc(j);
    end;
  end;
// main
begin
  if (Length(Chars) = 0) or (Interval <= 0) then
  begin
    Result := AValue;
    exit;
  end;

  // Calculate length based on original length and total extra length for control AnsiChars
  ALength := Length(AValue) + ((Length(AValue) - 1) div Interval + 3) * Length(Chars);
  SetLength(Result, ALength);

  // Copy and insert
  j := 1;
  for i := 1 to Length(AValue) do
  begin
    if (i mod Interval) = 1 then
      // Insert control AnsiChars
      InsertControlChars;
    Result[j] := AValue[i];
    inc(j);
  end;
  InsertControlChars;

  // Adjust length
  dec(j);
  if ALength > j then
    SetLength(Result, j);
end;

function sdRemoveControlChars(const AValue: UTF8String): UTF8String;
// Remove control characters from UTF8String in AValue
var
  i, j: integer;
begin
  Setlength(Result, Length(AValue));
  i := 1;
  j := 1;
  while i <= Length(AValue) do
    if AValue[i] in cControlChars then
      inc(i)
    else
    begin
      Result[j] := AValue[i];
      inc(i);
      inc(j);
    end;
  // Adjust length
  if i <> j then
    SetLength(Result, j - 1);
end;

function sdUTF8FindString(const SubString, S: UTF8String; Start, Close: integer; var APos: integer): boolean;
// Check if the Substring matches the UTF8String S in any position in interval Start to Close - 1
// and returns found positon in APos. Result = True if anything is found.
// Note: this funtion is case-insensitive
var
  CharIndex: integer;
begin
  Result := False;
  APos := 0;
  for CharIndex := Start to Close - Length(SubString) do
    if sdUTF8MatchString(SubString, S, CharIndex) then
    begin
      APos := CharIndex;
      Result := True;
      exit;
    end;
end;

function UTF8CompareText(const S1, S2: UTF8String): integer;
begin
  Result := AnsiCompareText(string(S1), string(S2));
end;

function IntToUTF8Str(Value: integer): UTF8String;
begin
  Result := UTF8String(IntToStr(Value));
end;

function Int64ToUTF8Str(Value: int64): UTF8String;
begin
  Result := UTF8String(IntToStr(Value));
end;

function sdUTF8MatchString(const SubString: UTF8String; const S: UTF8String; Start: integer): boolean;
// Check if the Substring matches the string S at position Start.
// Note: this funtion is case-insensitive
var
  CharIndex: integer;
begin
  Result := False;
  // Check range just in case
  if (Length(S) - Start + 1) < Length(Substring) then
    exit;

  CharIndex := 0;
  while CharIndex < Length(SubString) do
    if sdUpCase(SubString[CharIndex + 1]) = sdUpCase(S[Start + CharIndex]) then
      inc(CharIndex)
    else
      exit;
  // All AnsiChars were the same, so we succeeded
  Result := True;
end;

procedure sdUTF8ParseAttributes(const AValue: UTF8String; Start, Close: integer; Attributes: TsdUTF8StringList);
// Convert the attributes string AValue in [Start, Close - 1] to the attributes Stringlist
var
  i: integer;
  InQuotes: boolean;
  Quote: AnsiChar;
begin
  InQuotes := False;
  Quote := '"';
  if not assigned(Attributes) then
    exit;
  if not sdUTF8TrimPos(AValue, Start, Close) then
    exit;

  // Clear first
  Attributes.Clear;

  // Loop through characters
  for i := Start to Close - 1 do
  begin

    // In quotes?
    if InQuotes then
    begin
      if AValue[i] = Quote then
        InQuotes := False;
    end else
    begin
      if AValue[i] in cQuoteChars then
      begin
        InQuotes   := True;
        Quote := AValue[i];
      end;
    end;

    // Add attribute strings on each controlchar break
    if not InQuotes then
      if AValue[i] in cControlChars then
      begin
        if i > Start then
          Attributes.Add(copy(AValue, Start, i - Start));
        Start := i + 1;
      end;
  end;

  // Add last attribute string
  if Start < Close then
    Attributes.Add(copy(AValue, Start, Close - Start));

  // First-char "=" signs should append to previous
  for i := Attributes.Count - 1 downto 1 do
    if Attributes[i][1] = '=' then
    begin
      Attributes[i - 1] := Attributes[i - 1] + Attributes[i];
      Attributes.Delete(i);
    end;

  // First-char quotes should append to previous
  for i := Attributes.Count - 1 downto 1 do
    if (Attributes[i][1] in cQuoteChars) and (UTF8Pos('=', Attributes[i - 1]) > 0) then
    begin
      Attributes[i - 1] := Attributes[i - 1] + Attributes[i];
      Attributes.Delete(i);
    end;
end;

function sdUTF8TrimPos(const AValue: UTF8String; var Start, Close: integer): boolean;
// Trim the string in AValue in [Start, Close - 1] by adjusting Start and Close variables
begin
  // Checks
  Start := Max(1, Start);
  Close := Min(Length(AValue) + 1, Close);
  if Close <= Start then
  begin
    Result := False;
    exit;
  end;

  // Trim left
  while
    (Start < Close) and
    (AValue[Start] in cControlChars) do
    inc(Start);

  // Trim right
  while
    (Start < Close) and
    (AValue[Close - 1] in cControlChars) do
    dec(Close);

  // Do we have a string left?
  Result := Close > Start;
end;

function sdUTF8Trim(const AValue: UTF8String): UTF8String;
var
  Start, Close: integer;
  Res: boolean;
begin
  Start := 1;
  Close := length(AValue) + 1;
  Res := sdUTF8TrimPos(AValue, Start, Close);
  if Res then
    Result := Copy(AValue, Start, Close - Start)
  else
    Result := '';
end;

procedure sdUTF8WriteStringToStream(S: TStream; const AString: UTF8String);
begin
  if Length(AString) > 0 then
  begin
    {$IFDEF CLR}
    S.Write(BytesOf(AString), Length(AString));
    {$ELSE}
    S.Write(AString[1], Length(AString));
    {$ENDIF}
  end;
end;

function sdUpCase(Ch: AnsiChar): AnsiChar;
begin
  Result := Ch;
  case Result of
  'a'..'z':  Dec(Result, Ord('a') - Ord('A'));
  end;
end;

function ReadOpenTag(AReader: TsdSurplusReader): integer;
// Try to read the type of open tag from S
var
  AIndex, i: integer;
  Found: boolean;
  Ch: AnsiChar;
  Candidates: array[0..cTagCount - 1] of boolean;
  Surplus: UTF8String;
begin
  Surplus := '';
  Result := cTagCount - 1;
  for i := 0 to cTagCount - 1 do Candidates[i] := True;
  AIndex := 1;
  repeat
    Found := False;
    inc(AIndex);
    if AReader.ReadChar(Ch) = 0 then
      exit;
    Surplus := Surplus + UTF8String(Ch);
    for i := cTagCount - 1 downto 0 do
      if Candidates[i] and (length(cTags[i].Start) >= AIndex) then
      begin
        if cTags[i].Start[AIndex] = Ch then
        begin
          Found := True;
          if length(cTags[i].Start) = AIndex then
            Result := i;
        end else
          Candidates[i] := False;
      end;
  until Found = False;
  // The surplus string that we already read (everything after the tag)
  AReader.Surplus := copy(Surplus, length(cTags[Result].Start), length(Surplus));
end;

function ReadStringFromStreamUntil(AReader: TsdSurplusReader; const ASearch: UTF8String;
  var AValue: UTF8String; SkipQuotes: boolean): boolean;
var
  AIndex, ValueIndex, SearchIndex: integer;
  LastSearchChar, Ch: AnsiChar;
  InQuotes: boolean;
  QuoteChar: AnsiChar;
  SB: TsdStringBuilder;
begin
  Result := False;
  InQuotes := False;

  // Get last searchstring character
  AIndex := length(ASearch);
  if AIndex = 0 then exit;
  LastSearchChar := ASearch[AIndex];

  SB := TsdStringBuilder.Create;
  try
    QuoteChar := #0;

    repeat
      // Add characters to the value to be returned
      if AReader.ReadChar(Ch) = 0 then
        exit;
      SB.AddChar(Ch);

      // Do we skip quotes?
      if SkipQuotes then
      begin
        if InQuotes then
        begin
          if (Ch = QuoteChar) then
            InQuotes := false;
        end else
        begin
          if Ch in cQuoteChars then
          begin
            InQuotes := true;
            QuoteChar := Ch;
          end;
        end;
      end;

      // In quotes? If so, we don't check the end condition
      if not InQuotes then
      begin
        // Is the last char the same as the last char of the search string?
        if Ch = LastSearchChar then
        begin

          // Check to see if the whole search string is present
          ValueIndex  := SB.Length - 1;
          SearchIndex := length(ASearch) - 1;
          if ValueIndex < SearchIndex then continue;

          Result := True;
          while (SearchIndex > 0)and Result do
          begin
            Result := SB[ValueIndex] = ASearch[SearchIndex];
            dec(ValueIndex);
            dec(SearchIndex);
          end;
        end;
      end;
    until Result;

    // Use only the part before the search string
    AValue := SB.StringCopy(1, SB.Length - length(ASearch));
  finally
    SB.Free;
  end;
end;

function ReadStringFromStreamWithQuotes(S: TStream; const Terminator: UTF8String;
  var AValue: UTF8String): boolean;
var
  Ch, QuoteChar: AnsiChar;
  InQuotes: boolean;
  SB: TsdStringBuilder;
begin
  SB := TsdStringBuilder.Create;
  try
    QuoteChar := #0;
    Result := False;
    InQuotes := False;
    repeat
      if S.Read(Ch, 1) = 0 then exit;
      if not InQuotes then
      begin
        if (Ch = '"') or (Ch = '''') then
        begin
          InQuotes := True;
          QuoteChar := Ch;
        end;
      end else
      begin
        if Ch = QuoteChar then
          InQuotes := False;
      end;
      if not InQuotes and (UTF8String(Ch) = Terminator) then
        break;
      SB.AddChar(Ch);
    until False;
    AValue := SB.Value;
    Result := True;
  finally
    SB.Free;
  end;
end;

function GetTimeZoneBias: Integer;
// uses windows unit, func GetTimeZoneInformation
var
  TimeZoneInfo: TTimeZoneInformation;
begin
  case GetTimeZoneInformation(TimeZoneInfo) of
    TIME_ZONE_ID_UNKNOWN: Result := TimeZoneInfo.Bias;
    TIME_ZONE_ID_STANDARD: Result := TimeZoneInfo.Bias + TimeZoneInfo.StandardBias;
    TIME_ZONE_ID_DAYLIGHT: Result := TimeZoneInfo.Bias + TimeZoneInfo.DaylightBias;
  else
    Result := 0;
  end;
end;

function sdDateTimeFromString(const ADate: UTF8String; UseLocalBias: Boolean): TDateTime;
// Convert the string ADate to a TDateTime according to the W3C date/time specification
// as found here: http://www.w3.org/TR/NOTE-datetime
// contributor: Stefan Glienke
var
  AYear, AMonth, ADay, AHour, AMin, ASec, AMSec: word;
  ALocalBias, ABias: Integer;
begin
  AYear  := StrToInt(string(copy(ADate, 1, 4)));
  AMonth := StrToInt(string(copy(ADate, 6, 2)));
  ADay   := StrToInt(string(copy(ADate, 9, 2)));
  if Length(ADate) > 16 then
  begin
    AHour := StrToInt(string(copy(ADate, 12, 2)));
    AMin  := StrToInt(string(copy(ADate, 15, 2)));
    ASec  := StrToIntDef(string(copy(ADate, 18, 2)), 0); // They might be omitted, so default to 0
    AMSec := StrToIntDef(string(copy(ADate, 21, 3)), 0); // They might be omitted, so default to 0
  end else
  begin
    AHour := 0;
    AMin  := 0;
    ASec  := 0;
    AMSec := 0;
  end;
  Result :=
    EncodeDate(AYear, AMonth, ADay) +
    EncodeTime(AHour, AMin, ASec, AMSec);
  ALocalBias := GetTimeZoneBias;
  if UseLocalBias then
  begin
    if (Length(ADate) > 24) then
    begin
      ABias := StrToInt(string(Copy(ADate, 25, 2))) * MinsPerHour +
        StrToInt(string(Copy(ADate, 28, 2)));
      if ADate[24] = '+' then
        ABias := ABias * -1;
      Result := Result + ABias / MinsPerDay;
    end;
    Result := Result - ALocalBias / MinsPerDay;
  end;
end;

function sdDateTimeFromStringDefault(const ADate: UTF8String; ADefault: TDateTime; UseLocalBias: Boolean): TDateTime;
// Convert the string ADate to a TDateTime according to the W3C date/time specification
// as found here: http://www.w3.org/TR/NOTE-datetime
// If there is a conversion error, the default value ADefault is returned.
begin
  try
    Result := sdDateTimeFromString(ADate, UseLocalBias);
  except
    Result := ADefault;
  end;
end;

function sdDateTimeToString(ADate: TDateTime; UseLocalBias: Boolean): UTF8String;
// Convert the TDateTime ADate to a string according to the W3C date/time specification
// as found here: http://www.w3.org/TR/NOTE-datetime
// contributor: Stefan Glienke
var
  AYear, AMonth, ADay, AHour, AMin, ASec, AMSec: word;
  ABias: Integer;
const
  Neg: array[Boolean] of string = ('+', '-');
begin
  DecodeDate(ADate, AYear, AMonth, ADay);
  DecodeTime(ADate, AHour, AMin, ASec, AMSec);
  if frac(ADate) = 0 then
    Result := UTF8String(Format('%.4d-%.2d-%.2d', [AYear, AMonth, ADay]))
  else
  begin
    ABias := GetTimeZoneBias;
    if UseLocalBias and (ABias <> 0) then
      Result := UTF8String(Format('%.4d-%.2d-%.2dT%.2d:%.2d:%.2d.%.3d%s%.2d:%.2d',
        [AYear, AMonth, ADay, AHour, AMin, ASec, AMSec,
        Neg[ABias > 0], Abs(ABias) div MinsPerHour, Abs(ABias) mod MinsPerHour]))
    else
      Result := UTF8String(Format('%.4d-%.2d-%.2dT%.2d:%.2d:%.2d.%.3dZ',
        [AYear, AMonth, ADay, AHour, AMin, ASec, AMSec]));
  end;
end;

function sdWriteNumber(Value: double; SignificantDigits: integer; AllowScientific: boolean): UTF8String;
const
  Limits: array[1..9] of integer =
    (10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000);
var
  Limit, Limitd, PointPos, IntVal, ScPower: integer;
  Body: UTF8String;
begin
  if (SignificantDigits < 1) or (SignificantDigits > 9) then
    raise Exception.Create(sxeSignificantDigitsOutOfRange);

  // Zero
  if Value = 0 then
  begin
    Result := '0';
    exit;
  end;

  // Sign
  if Value < 0 then
  begin
    Result := '-';
    Value := -Value;
  end else
    Result := '';

  // Determine point position
  Limit := Limits[SignificantDigits];
  Limitd := Limit div 10;
  PointPos := SignificantDigits;
  while Value < Limitd do
  begin
    Value := Value * 10;
    dec(PointPos);
  end;
  while Value >= Limit do
  begin
    Value := Value * 0.1;
    inc(PointPos);
  end;

  // Round
  IntVal := round(Value);

  // Exceptional case which happens when the value rounds up to the limit
  if Intval = Limit then
  begin
    IntVal := IntVal div 10;
    inc(PointPos);
  end;

  // Strip off any zeros, these reduce significance count
  while (IntVal mod 10 = 0) and (PointPos < SignificantDigits) do
  begin
    dec(SignificantDigits);
    IntVal := IntVal div 10;
  end;

  // Check for scientific notation
  ScPower := 0;
  if AllowScientific and ((PointPos < -1) or (PointPos > SignificantDigits + 2)) then
  begin
    ScPower := PointPos - 1;
    dec(PointPos, ScPower);
  end;

  // Body
  Body := IntToUTF8Str(IntVal);
  while PointPos > SignificantDigits do
  begin
    Body := Body + '0';
    inc(SignificantDigits);
  end;
  while PointPos < 0 do
  begin
    Body := '0' + Body;
    inc(PointPos);
  end;
  if PointPos = 0 then
    Body := '.' + Body
  else
    if PointPos < SignificantDigits then
      Body := copy(Body, 1, PointPos) + '.' + copy(Body, PointPos + 1, SignificantDigits);

  // Final result
  if ScPower = 0 then
    Result := Result + Body
  else
    Result := Result + Body + 'E' + IntToUTF8Str(ScPower);
end;

{$IFDEF CLR}

function sdUnicodeToUtf8(const W: UnicodeString): UTF8String;
begin
  Result := Encoding.UTF8.GetBytes(W);
end;

function sdUtf8ToUnicode(const S: UTF8String): UnicodeString;
begin
  Result := Encoding.UTF8.GetString(BytesOf(S));
end;

function EncodeBase64Buf(const Buffer: TBytes; Count: Integer): UTF8String;
begin
  Result := Convert.ToBase64String(Buffer, 0, Count);
end;

function EncodeBase64(const Source: UTF8String): UTF8String;
begin
  Result := Convert.ToBase64String(BytesOf(Source));
end;

procedure DecodeBase64Buf(const Source: UTF8String; var Buffer: TBytes; Count: Integer);
var
  ADecoded: TBytes;
begin
  ADecoded := Convert.FromBase64String(Source);
  if Count > Length(ADecoded) then
    raise EFilerError.Create(sxeMissingDataInBinaryStream);
  SetLength(ADecoded, Count);
  Buffer := ADecoded;
end;

function DecodeBase64(const Source: UTF8String): UTF8String;
begin
  Result := UTF8String(Convert.FromBase64String(Source));
end;

{$ELSE}

function PtrUnicodeToUtf8(Dest: PAnsiChar; MaxDestBytes: Cardinal; Source: PUnicodeChar; SourceChars: Cardinal): Cardinal;
var
  i, count: Cardinal;
  c: Cardinal;
begin
  Result := 0;
  if not assigned(Source) or not assigned(Dest) then
    exit;

  count := 0;
  i := 0;

  while (i < SourceChars) and (count < MaxDestBytes) do
  begin
    c := Cardinal(Source[i]);
    Inc(i);
    if c <= $7F then
    begin
      Dest[count] := AnsiChar(c);
      Inc(count);
    end else
      if c > $7FF then
      begin
        if count + 3 > MaxDestBytes then
          break;
        Dest[count] := AnsiChar($E0 or (c shr 12));
        Dest[count+1] := AnsiChar($80 or ((c shr 6) and $3F));
        Dest[count+2] := AnsiChar($80 or (c and $3F));
        Inc(count,3);
      end else
      begin //  $7F < Source[i] <= $7FF
        if count + 2 > MaxDestBytes then
          break;
        Dest[count] := AnsiChar($C0 or (c shr 6));
        Dest[count+1] := AnsiChar($80 or (c and $3F));
        Inc(count,2);
      end;
  end;
  if count >= MaxDestBytes then
    count := MaxDestBytes-1;
  Dest[count] := #0;
  Result := count + 1;  // convert zero based index to byte count
end;

function PtrUtf8ToUnicode(Dest: PUnicodeChar; MaxDestChars: Cardinal; Source: PAnsiChar;
  SourceBytes: Cardinal): Cardinal;
var
  i, count: Cardinal;
  c: Byte;
  wc: Cardinal;
begin
  if not assigned(Dest) or not assigned(Source) then
  begin
    Result := 0;
    Exit;
  end;
  Result := Cardinal(-1);
  count := 0;
  i := 0;
  while (i < SourceBytes) and (count < MaxDestChars) do
  begin
    wc := Cardinal(Source[i]);
    Inc(i);
    if (wc and $80) <> 0 then
    begin
      if i >= SourceBytes then
        // incomplete multibyte char
        Exit;
      wc := wc and $3F;
      if (wc and $20) <> 0 then
      begin
        c := Byte(Source[i]);
        Inc(i);
        if (c and $C0) <> $80 then
          // malformed trail byte or out of range char
          Exit;
        if i >= SourceBytes then
          // incomplete multibyte char
          Exit;
        wc := (wc shl 6) or (c and $3F);
      end;
      c := Byte(Source[i]);
      Inc(i);
      if (c and $C0) <> $80 then
        // malformed trail byte
        Exit;
      Dest[count] := UnicodeChar((wc shl 6) or (c and $3F));
    end else
      Dest[count] := UnicodeChar(wc);
    Inc(count);
  end;

  if count >= MaxDestChars then
    count := MaxDestChars-1;

  Dest[count] := #0;
  Result := count + 1;
end;

function sdUnicodeToUtf8(const W: UnicodeString): UTF8String;
var
  L: integer;
  Temp: UTF8String;
begin
  Result := '';
  if W = '' then
    Exit;
  SetLength(Temp, Length(W) * 3); // SetLength includes space for null terminator

  L := PtrUnicodeToUtf8(PAnsiChar(Temp), Length(Temp) + 1, PUnicodeChar(W), Length(W));
  if L > 0 then
    SetLength(Temp, L - 1)
  else
    Temp := '';
  Result := Temp;
end;

function sdUtf8ToUnicode(const S: UTF8String): UnicodeString;
var
  L: Integer;
  Temp: UnicodeString;
begin
  Result := '';
  if S = '' then
    Exit;
  SetLength(Temp, Length(S));

  L := PtrUtf8ToUnicode(PUnicodeChar(Temp), Length(Temp)+1, PAnsiChar(S), Length(S));
  if L > 0 then
    SetLength(Temp, L-1)
  else
    Temp := '';
  Result := Temp;
end;

function EncodeBase64Buf(const Buffer; Count: Integer): UTF8String;
var
  i, j: integer;
  ACore: integer;
  ALong: cardinal;
  S: PByte;
begin
  // Make sure ASize is always a multiple of 3, and this multiple
  // gets saved as 4 characters
  ACore := (Count + 2) div 3;

  // Set the length of the string that stores encoded characters
  SetLength(Result, ACore * 4);
  S := @Buffer;
  // Do the loop ACore times
  for i := 0 to ACore - 1 do
  begin
    ALong := 0;
    for j := 0 to 2 do
    begin
      ALong := ALong shl 8 + S^;
      inc(S);
    end;
    for j := 0 to 3 do
    begin
      Result[i * 4 + 4 - j] := cBase64Char[ALong and $3F];
      ALong := ALong shr 6;
    end;
  end;
  // For comformity to Base64, we must pad the data instead of zero out
  // if the size is not an exact multiple of 3
  case ACore * 3 - Count of
  0:;// nothing to do
  1: // pad one byte
    Result[ACore * 4] := cBase64PadChar;
  2: // pad two bytes
    begin
      Result[ACore * 4    ] := cBase64PadChar;
      Result[ACore * 4 - 1] := cBase64PadChar;
    end;
  end;//case
end;

function EncodeBase64(const Source: RawByteString): UTF8String;
// Encode binary data in Source as BASE64. The function returns the BASE64 encoded
// data as string, without any linebreaks.
begin
  if length(Source) > 0 then
    Result := EncodeBase64Buf(Source[1], length(Source))
  else
    Result := '';
end;

procedure DecodeBase64Buf(var Source: UTF8String; var Buffer; Count: Integer);
var
  i, j: integer;
  BufPos, Core: integer;
  LongVal: cardinal;
  D: PByte;
  Map: array[AnsiChar] of byte;
begin
  // Core * 4 is the number of chars to read - check length
  Core := Length(Source) div 4;
  if Count > Core * 3 then
    raise EFilerError.Create(sxeMissingDataInBinaryStream);

  // Prepare map
  for i := 0 to 63 do
    Map[cBase64Char[i]] := i;
  D := @Buffer;

  // Check for final padding, and replace with "zeros". There can be
  // at max two pad chars ('=')
  BufPos := length(Source);
  if (BufPos > 0) and (Source[BufPos] = cBase64PadChar) then
  begin
    Source[BufPos] := cBase64Char[0];
    dec(BufPos);
    if (BufPos > 0) and (Source[BufPos] = cBase64PadChar) then
      Source[BufPos] := cBase64Char[0];
  end;

  // Do this Core times
  for i := 0 to Core - 1 do
  begin
    LongVal := 0;
    // Unroll the characters
    for j := 0 to 3 do
      LongVal := LongVal shl 6 + Map[Source[i * 4 + j + 1]];
    // and unroll the bytes
    for j := 2 downto 0 do
    begin
      // Check overshoot
      if integer(D) - integer(@Buffer) >= Count then
        exit;
      D^ := LongVal shr (j * 8) and $FF;
      inc(D);
    end;
  end;
end;

function DecodeBase64(const Source: UTF8String): RawByteString;
// Decode BASE64 data in Source into binary data. The function returns the binary
// data as UTF8String. Use a TStringStream to convert this data to a stream.
var
  BufData: UTF8String;
  BufSize, BufPos: integer;
begin
  BufData := sdRemoveControlChars(Source);

  // Determine length of data
  BufSize := length(BufData) div 4;
  if BufSize * 4 <> length(BufData) then
    raise EFilerError.Create(sxeErrorCalcStreamLength);
  BufSize := BufSize * 3;
  // Check padding AnsiChars
  BufPos := length(BufData);
  if (BufPos > 0) and (BufData[BufPos] = cBase64PadChar) then
  begin
    dec(BufPos);
    dec(BufSize);
    if (BufPos > 0) and (BufData[BufPos] = cBase64PadChar) then
      dec(BufSize);
  end;
  Setlength(Result, BufSize);

  // Decode
  if BufSize > 0 then
    DecodeBase64Buf(BufData, Result[1], BufSize);
end;

{$ENDIF}

function sdAnsiToUtf8(const S: AnsiString): UTF8String;
begin
  // We let the OS figure out Ansi<->Unicode
  Result := sdUnicodeToUtf8(UnicodeString(S));
end;

function sdUtf8ToAnsi(const S: UTF8String): AnsiString;
begin
  // We let the OS figure out Ansi<->Unicode. There might be dataloss!
  Result := Ansistring(sdUtf8ToUnicode(S));
end;

function EncodeBinHexBuf(const Source; Count: Integer): UTF8String;
// Encode binary data in Source as BINHEX. The function returns the BINHEX encoded
// data as UTF8String, without any linebreaks.
var
{$IFDEF CLR}
  Text: TBytes;
{$ELSE}
  Text: UTF8String;
{$ENDIF}
begin
  SetLength(Text, Count * 2);
{$IFDEF CLR}
  BinToHex(TBytes(Source), 0, Text, 0, Count);
{$ELSE}
  BinToHex(PAnsiChar(@Source), PAnsiChar(Text), Count);
{$ENDIF}
  Result := Text;
end;

function EncodeBinHex(const Source: RawByteString): UTF8String;
// Encode binary data in Source as BINHEX. The function returns the BINHEX encoded
// data as UTF8String, without any linebreaks.
var
{$IFDEF CLR}
  Text: TBytes;
{$ELSE}
  Text: UTF8String;
{$ENDIF}
begin
  SetLength(Text, Length(Source) * 2);
{$IFDEF CLR}
  BinToHex(BytesOf(Source), 0, Text, 0, Length(Source));
{$ELSE}
  BinToHex(PAnsiChar(Source), PAnsiChar(Text), Length(Source));
{$ENDIF}
  Result := Text;
end;

procedure DecodeBinHexBuf(const Source: UTF8String; var Buffer{$IFDEF CLR}: TBytes{$ENDIF}; Count: Integer);
// Decode BINHEX data in Source into binary data.
begin
  if Length(Source) div 2 < Count then
    raise EFilerError.Create(sxeMissingDataInBinaryStream);

{$IFDEF CLR}
  HexToBin(BytesOf(Source), 0, Buffer, 0, Count);
{$ELSE}
  HexToBin(PAnsiChar(Source), PAnsiChar(@Buffer), Count);
{$ENDIF}
end;

function DecodeBinHex(const Source: UTF8String): RawByteString;
// Decode BINHEX data in Source into binary data. The function returns the binary
// data as RawByteString. Use a TStringStream to convert this data to a stream.
var
  Data: Utf8String;
  Size: integer;
{$IFDEF CLR}
  Buffer: TBytes;
{$ELSE}
  Buffer: RawByteString;
{$ENDIF}
begin
  Data := sdRemoveControlChars(Source);

  // Determine length of data
  Size := length(Data) div 2;
  if Size * 2 <> length(Data) then
    raise EFilerError.Create(sxeErrorCalcStreamLength);

  SetLength(Buffer, Size);
{$IFDEF CLR}
  HexToBin(BytesOf(Data), 0, Buffer, 0, Size);
{$ELSE}
  HexToBin(PAnsiChar(Data), PAnsiChar(Buffer), Size);
{$ENDIF}
  Result := Buffer;
end;

function sdStringToBool(const AValue: UTF8String): boolean;
var
  Ch: AnsiChar;
begin
  if Length(AValue) > 0 then
  begin
    Ch := sdUpCase(AValue[1]);
    if Ch in ['T', 'Y', '1'] then
    begin
      Result := True;
      exit;
    end;
    if Ch in ['F', 'N', '0'] then
    begin
      Result := False;
      exit;
    end;
  end;
  raise Exception.Create(sxeCannotConverToBool);
end;

function sdStringFromBool(ABool: boolean): UTF8String;
const
  cBoolValues: array[boolean] of UTF8String = ('false', 'true');
begin
  Result := cBoolValues[ABool];
end;

{ TsdUTF8StringList }

function TsdUTF8StringList.Add(const S: UTF8String): integer;
var
  L: integer;
begin
  L := Length(FItems);
  if L = FCount then
  begin
    // Increase capacity
    SetLength(FItems, FCount + 4);
  end;
  FItems[FCount] := S;
  Result := FCount;
  inc(FCount);
end;

procedure TsdUTF8StringList.Assign(Source: TPersistent);
var
  i: integer;
  SL: TsdUTF8StringList;
begin
  if Source is TsdUTF8StringList then
  begin
    SL := TsdUTF8StringList(Source);
    SetLength(FItems, SL.FCount);
    for i := 0 to SL.FCount - 1 do
      FItems[i] := SL.FItems[i];
    FCount := SL.FCount;
  end else
    inherited;
end;

procedure TsdUTF8StringList.Clear;
begin
  FCount := 0;
end;

procedure TsdUTF8StringList.Delete(Index: Integer);
var
  i: integer;
begin
  if (Index < 0) or (Index >= Count) then
    exit;
  for i := Index + 1 to Count - 1 do
    FItems[i - 1] := FItems[i];
  dec(FCount);
end;

function TsdUTF8StringList.GetItems(Index: integer): UTF8String;
begin
  if (Index >= 0) and (Index < Count) then
    Result := FItems[Index]
  else
    Result := '';
end;

function TsdUTF8StringList.GetNames(Index: integer): UTF8String;
var
  P: integer;
begin
  Result := Items[Index];
  P := UTF8Pos('=', Result);
  if P <> 0 then
    SetLength(Result, P - 1)
  else
    SetLength(Result, 0);
end;

function TsdUTF8StringList.GetText: UTF8String;
const
  cLB: UTF8String = #13#10;
var
  i, L, LItem: integer;
  P: PAnsiChar;
begin
  L := 0;
  for i := 0 to Count - 1 do
  begin
    inc(L, length(FItems[i]));
    inc(L, 2);
  end;
  SetLength(Result, L);
  if L = 0 then
    exit;
  P := @Result[1];
  for i := 0 to Count - 1 do
  begin
    LItem := length(FItems[i]);
    if LItem > 0 then
    begin
      System.Move(FItems[i][1], P^, LItem);
      inc(P, LItem);
    end;
    System.Move(cLB[1], P^, 2);
    inc(P, 2);
  end;
end;

function TsdUTF8StringList.GetValues(const Name: UTF8String): UTF8String;
var
  Idx: integer;
begin
  Idx := IndexOfName(Name);
  if Idx >= 0 then
    Result := Copy(FItems[Idx], Length(Name) + 2, MaxInt)
  else
    Result := '';
end;

function TsdUTF8StringList.IndexOfName(const Name: UTF8String): integer;
begin
  for Result := 0 to Count - 1 do
  begin
    if sdUTF8MatchString(Name + '=', FItems[Result], 1) then
      exit;
  end;
  Result := -1;
end;

procedure TsdUTF8StringList.SetItems(Index: integer; const Value: UTF8String);
begin
  if (Index >= 0) and (Index < Count) then
    FItems[Index] := Value;
end;

procedure TsdUTF8StringList.SetValues(const Name, Value: UTF8String);
var
  Idx: integer;
begin
  Idx := IndexOfName(Name);
  if Value <> '' then
  begin
    if Idx < 0 then
      Idx := Add('');
    FItems[Idx] := Name + '=' + Value;
  end else
    Delete(Idx);
end;

{ TXmlNode }

function TXmlNode.AbortParsing: boolean;
begin
  Result := assigned(Document) and Document.AbortParsing;
end;

procedure TXmlNode.Assign(Source: TPersistent);
var
  i: integer;
  Node: TXmlNode;
begin
  if Source is TXmlNode then
  begin
    // Clear first
    Clear;

    // Properties
    FElementType := TXmlNode(Source).FElementType;
    FName := TXmlNode(Source).FName;
    FTag := TXmlNode(Source).FTag;
    FValue := TXmlNode(Source).FValue;

    // Attributes
    if assigned(TXmlNode(Source).FAttributes) then
    begin
      CheckCreateAttributesList;
      FAttributes.Assign(TXmlNode(Source).FAttributes);
    end;

    // Nodes
    for i := 0 to TXmlNode(Source).NodeCount - 1 do
    begin
      Node := NodeNew('');
      Node.Assign(TXmlNode(Source).Nodes[i]);
    end;
  end else
    if Source is TNativeXml then
    begin
      Assign(TNativeXml(Source).FRootNodes);
    end else
      inherited;
end;

procedure TXmlNode.AttributeAdd(const AName, AValue: UTF8String);
var
  Attr: UTF8String;
begin
  Attr := UTF8String(Format('%s=%s', [AName, sdUTF8QuotedString(sdUTF8EscapeString(AValue))]));
  CheckCreateAttributesList;
  FAttributes.Add(Attr);
end;

procedure TXmlNode.AttributeAdd(const AName: UTF8String; AValue: integer);
begin
  AttributeAdd(AName, IntToUTF8Str(AValue));
end;

procedure TXmlNode.AttributeDelete(Index: integer);
begin
  if (Index >= 0) and (Index < AttributeCount) then
    FAttributes.Delete(Index);
end;

procedure TXmlNode.AttributeExchange(Index1, Index2: integer);
var
  Temp: UTF8String;
begin
  if (Index1 <> Index2) and
     (Index1 >= 0) and (Index1 < FAttributes.Count) and
     (Index2 >= 0) and (Index2 < FAttributes.Count) then
  begin
    Temp := FAttributes[Index1];
    FAttributes[Index1] := FAttributes[Index2];
    FAttributes[Index2] := Temp;
  end;
end;

function TXmlNode.AttributeIndexByname(const AName: UTF8String): integer;
// Return the index of the attribute with name AName, or -1 if not found
begin
  if assigned(FAttributes) then
    Result := FAttributes.IndexOfName(AName)
  else
    Result := -1;
end;

procedure TXmlNode.AttributesClear;
begin
  FreeAndNil(FAttributes);
end;

function TXmlNode.BufferLength: integer;
var
  BufData: UTF8String;
  BufPos: integer;
begin
  BufData := sdRemoveControlChars(FValue);
  case BinaryEncoding of
  xbeBinHex:
    begin
      Result := length(BufData) div 2;
      if Result * 2 <> length(BufData) then
        raise EFilerError.Create(sxeErrorCalcStreamLength);
    end;
  xbeBase64:
    begin
      Result := length(BufData) div 4;
      if Result * 4 <> length(BufData) then
        raise EFilerError.Create(sxeErrorCalcStreamLength);
      Result := Result * 3;
      // Check padding AnsiChars
      BufPos := length(BufData);
      if (BufPos > 0) and (BufData[BufPos] = cBase64PadChar) then
      begin
        dec(BufPos);
        dec(Result);
        if (BufPos > 0) and (BufData[BufPos] = cBase64PadChar) then
          dec(Result);
      end;
    end;
  else
    Result := 0; // avoid compiler warning
  end;
end;

procedure TXmlNode.BufferRead(var Buffer{$IFDEF CLR}: TBytes{$ENDIF}; Count: Integer);
// Read data from XML binhex to the buffer
var
  BufData: UTF8String;
begin
  BufData := sdRemoveControlChars(FValue);
  case BinaryEncoding of
  xbeBinHex:
    DecodeBinHexBuf(BufData, Buffer, Count);
  xbeBase64:
    DecodeBase64Buf(BufData, Buffer, Count);
  end;
end;

procedure TXmlNode.BufferWrite(const Buffer{$IFDEF CLR}: TBytes{$ENDIF}; Count: Integer);
// Write data from the buffer to XML in binhex or base64 format
var
  BufData: UTF8String;
begin
  if Count > 0 then
    case BinaryEncoding of
    xbeBinHex:
      BufData := EncodeBinHexBuf(Buffer, Count);
    xbeBase64:
      BufData := EncodeBase64Buf(Buffer, Count);
    end;

  // For comformity with Base64, we must add linebreaks each 76 AnsiCharacters
  FValue := sdAddControlChars(BufData, GetLineFeed + GetIndent, 76);
end;

procedure TXmlNode.ChangeDocument(ADocument: TNativeXml);
var
  i: integer;
begin
  FDocument := ADocument;
  for i := 0 to NodeCount - 1 do
    Nodes[i].ChangeDocument(ADocument);
end;

procedure TXmlNode.CheckCreateAttributesList;
begin
  if not assigned(FAttributes) then
    FAttributes := TsdUTF8StringList.Create;
end;

procedure TXmlNode.Clear;
begin
  // Name + value
  FName  := '';
  FValue := '';
  // Clear attributes and nodes
  AttributesClear;
  NodesClear;
end;

function TXmlNode.CompareNodeName(const NodeName: UTF8String): integer;
begin
  // Compare with FullPath or local name based on NodeName's first AnsiCharacter
  if length(NodeName) > 0 then
    if NodeName[1] = '/' then
    begin
      // FullPath
      Result := UTF8CompareText(FullPath, NodeName);
      exit;
    end;
  // local name
  Result := UTF8CompareText(Name, NodeName);
end;

constructor TXmlNode.Create(ADocument: TNativeXml);
begin
  inherited Create;
  FDocument := ADocument;
end;

constructor TXmlNode.CreateName(ADocument: TNativeXml; const AName: UTF8String);
begin
  Create(ADocument);
  Name := AName;
end;

constructor TXmlNode.CreateNameValue(ADocument: TNativeXml; const AName, AValue: UTF8String);
begin
  Create(ADocument);
  Name := AName;
  ValueAsString := AValue;
end;

constructor TXmlNode.CreateType(ADocument: TNativeXml;
  AType: TXmlElementType);
begin
  Create(ADocument);
  FElementType  := AType;
end;

procedure TXmlNode.Delete;
begin
  if assigned(Parent) then
    Parent.NodeRemove(Self);
end;

procedure TXmlNode.DeleteEmptyAttributes;
var
  i: integer;
  V: UTF8String;
begin
 for i := AttributeCount - 1 downto 0 do
 begin
   V := AttributeValue[i];
   if length(V) = 0 then
     FAttributes.Delete(i);
 end;
end;

procedure TXmlNode.DeleteEmptyNodes;
var
  i: integer;
  Node: TXmlNode;
begin
  for i := NodeCount - 1 downto 0 do
  begin
    Node := Nodes[i];
    // Recursive call
    Node.DeleteEmptyNodes;
    // Check if we should delete child node
    if Node.IsEmpty then
      NodeDelete(i);
  end;
end;

destructor TXmlNode.Destroy;
begin
  NodesClear;
  AttributesClear;
  inherited;
end;

function TXmlNode.FindNode(const NodeName: UTF8String): TXmlNode;
// Find the first node which has name NodeName. Contrary to the NodeByName
// function, this function will search the whole subnode tree, using the
// DepthFirst method.
var
  i: integer;
begin
  Result := nil;
  // Loop through all subnodes
  for i := 0 to NodeCount - 1 do
  begin
    Result := Nodes[i];
    // If the subnode has name NodeName then we have a result, exit
    if Result.CompareNodeName(NodeName) = 0 then
      exit;
    // If not, we will search the subtree of this node
    Result := Result.FindNode(NodeName);
    if assigned(Result) then
      exit;
  end;
end;

procedure TXmlNode.FindNodes(const NodeName: UTF8String; const AList: TList);
  // local
  procedure FindNodesRecursive(ANode: TXmlNode; AList: TList);
  var
    i: integer;
  begin
    with ANode do
      for i := 0 to NodeCount - 1 do
      begin
        if Nodes[i].CompareNodeName(NodeName) = 0 then
          AList.Add(Nodes[i]);
        FindNodesRecursive(Nodes[i], AList);
      end;
  end;
// main
begin
  AList.Clear;
  FindNodesRecursive(Self, AList);
end;

function TXmlNode.FloatAllowScientific: boolean;
begin
  if assigned(Document) then
    Result := Document.FloatAllowScientific
  else
    Result := cDefaultFloatAllowScientific;
end;

function TXmlNode.FloatSignificantDigits: integer;
begin
  if assigned(Document) then
    Result := Document.FloatSignificantDigits
  else
    Result := cDefaultFloatSignificantDigits;
end;

function TXmlNode.FromAnsiString(const s: AnsiString): UTF8String;
begin
  Result := sdAnsiToUtf8(s)
end;

function TXmlNode.FromUnicodeString(const W: UnicodeString): UTF8String;
begin
  Result := sdUnicodeToUtf8(W)
end;

function TXmlNode.GetAttributeByName(const AName: UTF8String): UTF8String;
begin
  if assigned(FAttributes) then
    Result := sdUTF8UnEscapeString(sdUTF8UnQuotedString(FAttributes.Values[AName]))
  else
    Result := '';
end;

function TXmlNode.GetAttributeByNameWide(const AName: UTF8String): UnicodeString;
begin
  Result := ToUnicodeString(GetAttributeByName(AName));
end;

function TXmlNode.GetAttributeCount: integer;
begin
  if assigned(FAttributes) then
    Result := FAttributes.Count
  else
    Result := 0;
end;

function TXmlNode.GetAttributeName(Index: integer): UTF8String;
begin
  if (Index >= 0) and (Index < AttributeCount) then
    Result := FAttributes.Names[Index];
end;

function TXmlNode.GetAttributePair(Index: integer): UTF8String;
begin
  if (Index >= 0) and (Index < AttributeCount) then
    Result := FAttributes[Index];
end;

function TXmlNode.GetAttributeValue(Index: integer): UTF8String;
var
  P: integer;
  S: UTF8String;
begin
  Result := '';
  if (Index >= 0) and (Index < AttributeCount) then
  begin
    S := FAttributes[Index];
    P := Utf8Pos('=', S);
    if P > 0 then
      Result := sdUTF8UnEscapeString(sdUTF8UnQuotedString(Copy(S, P + 1, MaxInt)));
  end;
end;

function TXmlNode.GetAttributeValueAsInteger(Index: integer): integer;
begin
  Result := StrToIntDef(string(GetAttributeValue(Index)), 0);
end;

function TXmlNode.GetAttributeValueAsUnicodeString(Index: integer): UnicodeString;
begin
  Result := ToUnicodeString(GetAttributeValue(Index));
end;

function TXmlNode.GetAttributeValueDirect(Index: integer): UTF8String;
var
  P: integer;
  S: UTF8String;
begin
  Result := '';
  if (Index >= 0) and (Index < AttributeCount) then
  begin
    S := FAttributes[Index];
    P := Utf8Pos('=', S);
    if P > 0 then
      Result := sdUTF8UnQuotedString(Copy(S, P + 1, MaxInt));
  end;
end;

function TXmlNode.GetBinaryEncoding: TBinaryEncodingType;
begin
  Result := xbeBinHex;
  if assigned(Document) then
    Result := Document.BinaryEncoding;
end;

function TXmlNode.GetBinaryString: RawByteString;
// Get the binary contents of this node as Base64 and return it as a RawByteString
var
  OldEncoding: TBinaryEncodingType;
{$IFDEF CLR}
  Buffer: TBytes;
{$ENDIF}
begin
  // Set to base64
  OldEncoding := BinaryEncoding;
  try
    BinaryEncoding := xbeBase64;
    {$IFDEF CLR}
    SetLength(Buffer, BufferLength);
    if length(Buffer) > 0 then
      BufferRead(Buffer, length(Buffer));
    Result := Buffer;
    {$ELSE}
    SetLength(Result, BufferLength);
    if length(Result) > 0 then
      BufferRead(Result[1], length(Result));
    {$ENDIF}
  finally
    BinaryEncoding := OldEncoding;
  end;
end;

function TXmlNode.GetCascadedName: UTF8String;
// Return the name+index and all predecessors with underscores to separate, in
// order to get a unique reference that can be used in filenames
var
  LName: UTF8String;
begin
  LName :=  UTF8String(Format('%s%.4d', [Name, StrToIntDef(string(AttributeByName['Index']), 0)]));
  if assigned(Parent) then
    Result := UTF8String(Format('%s_%s', [Parent.CascadedName, LName]))
  else
    Result := LName;
end;

function TXmlNode.GetFullPath: UTF8String;
// GetFullpath will return the complete path of the node from the root, e.g.
// /Root/SubNode1/SubNode2/ThisNode
begin
  Result := '/' + Name;
  if Treedepth > 0 then
    // Recursive call
    Result := Parent.GetFullPath + Result;
end;

function TXmlNode.GetIndent: UTF8String;
var
  i: integer;
begin
  if assigned(Document) then
  begin
    case Document.XmlFormat of
    xfCompact: Result := '';
    xfReadable:
      for i := 0 to TreeDepth - 1 do
        Result := Result + Document.IndentString;
    end; //case
  end else
    Result := ''
end;

function TXmlNode.GetLineFeed: UTF8String;
begin
  if assigned(Document) then
  begin
    case Document.XmlFormat of
    xfCompact:  Result := '';
    xfReadable: Result := #13#10;
    else
      Result := #10;
    end; //case
  end else
    Result := '';
end;

function TXmlNode.GetNodeCount: integer;
begin
  if Assigned(FNodes) then
    Result := FNodes.Count
  else
    Result := 0;
end;

function TXmlNode.GetNodes(Index: integer): TXmlNode;
begin
  if (Index >= 0) and (Index < NodeCount) then
    Result := TXmlNode(FNodes[Index])
  else
    Result := nil;
end;

function TXmlNode.GetTotalNodeCount: integer;
var
  i: integer;
begin
  Result := NodeCount;
  for i := 0 to NodeCount - 1 do
    inc(Result, Nodes[i].TotalNodeCount);
end;

function TXmlNode.GetTreeDepth: integer;
begin
  Result := -1;
  if assigned(Parent) then
    Result := Parent.TreeDepth + 1;
end;

function TXmlNode.GetValueAsBool: boolean;
begin
  Result := sdStringToBool(FValue);
end;

function TXmlNode.GetValueAsDateTime: TDateTime;
begin
  Result := sdDateTimeFromString(ValueAsString, UseLocalBias);
end;

function TXmlNode.GetValueAsFloat: double;
var
  Code: integer;
begin
  val(string(sdUTF8StringReplace(FValue, ',', '.')), Result, Code);
  if Code > 0 then
    raise Exception.Create(sxeCannotConvertToFloat);
end;

function TXmlNode.GetValueAsInt64: int64;
begin
  Result := StrToInt64(string(FValue));
end;

function TXmlNode.GetValueAsInteger: integer;
begin
  Result := StrToInt(string(FValue));
end;

function TXmlNode.GetValueAsString: UTF8String;
begin
  if FElementType = xeNormal then
    Result := UnEscapeString(sdUTF8Trim(FValue))
  else
    Result := UnEscapeString(FValue);
end;

function TXmlNode.GetValueAsUnicodeString: UnicodeString;
begin
  Result := ToUnicodeString(ValueAsString);
end;

function TXmlNode.GetWriteOnDefault: boolean;
begin
  Result := True;
  if assigned(Document) then
    Result := Document.WriteOnDefault;
end;

function TXmlNode.HasAttribute(const AName: UTF8String): boolean;
begin
  if assigned(FAttributes) then
    Result := FAttributes.IndexOfName(AName) >= 0
  else
    Result := False;
end;

function TXmlNode.IndexInParent: integer;
// Retrieve our index in the parent's nodelist
begin
  Result := -1;
  if assigned(Parent) then
    Result := Parent.FNodes.IndexOf(Self);
end;

function TXmlNode.IsClear: boolean;
begin
  Result := (Length(FName) = 0) and IsEmpty;
end;

function TXmlNode.IsEmpty: boolean;
begin
  Result := (Length(FValue) = 0) and (NodeCount = 0) and (AttributeCount = 0);
end;

function TXmlNode.IsEqualTo(ANode: TXmlNode; Options: TXmlCompareOptions;
  MismatchNodes: TList): boolean;
var
  i, Index: integer;
  NodeResult, ChildResult: boolean;
begin
  // Start with a negative result
  Result := False;
  NodeResult := False;
  if not assigned(ANode) then
    exit;

  // Assume childs equals other node's childs
  ChildResult := True;

  // child node names and values - this comes first to assure the lists are filled
  if (xcChildNames in Options) or (xcChildValues in Options) or (xcRecursive in Options) then
    for i := 0 to NodeCount - 1 do
    begin
      // Do child name check
      Index := ANode.NodeIndexByName(Nodes[i].Name);
      // Do we have the childnode in the other?
      if Index < 0 then
      begin
        // No we dont have it
        if xcChildNames in Options then
        begin
          if assigned(MismatchNodes) then MismatchNodes.Add(Nodes[i]);
          ChildResult := False;
        end;
      end else
      begin
        // Do child value check
        if xcChildValues in Options then
          if UTF8CompareText(Nodes[i].ValueAsString, ANode.Nodes[Index].ValueAsString) <> 0 then
          begin
            if assigned(MismatchNodes) then
              MismatchNodes.Add(Nodes[i]);
            ChildResult := False;
          end;
        // Do recursive check
        if xcRecursive in Options then
          if not Nodes[i].IsEqualTo(ANode.Nodes[Index], Options, MismatchNodes) then
            ChildResult := False;
      end;
    end;

  try
    // We assume there are differences
    NodeResult := False;

    // Node name, type and value
    if xcNodeName in Options then
      if UTF8CompareText(Name, ANode.Name) <> 0 then
        exit;

    if xcNodeType in Options then
      if ElementType <> ANode.ElementType then
        exit;

    if xcNodeValue in Options then
      if UTF8CompareText(ValueAsString, ANode.ValueAsString) <> 0 then
        exit;

    // attribute count
    if xcAttribCount in Options then
      if AttributeCount <> ANode.AttributeCount then
        exit;

    // attribute names and values
    if (xcAttribNames in Options) or (xcAttribValues in Options) then
      for i := 0 to AttributeCount - 1 do
      begin
        Index := ANode.AttributeIndexByName(AttributeName[i]);
        if Index < 0 then
          if xcAttribNames in Options then
            exit
          else
            continue;
        if xcAttribValues in Options then
          if UTF8CompareText(AttributeValue[i], ANode.AttributeValue[Index]) <> 0 then
            exit;
      end;

    // child node count
    if xcChildCount in Options then
      if NodeCount <> ANode.NodeCount then
        exit;

    // If we arrive here, it means no differences were found, return True
    NodeResult := True;

  finally

    Result := ChildResult and NodeResult;
    if (not NodeResult) and assigned(MismatchNodes) then
      MismatchNodes.Insert(0, Self);

  end;
end;

function TXmlNode.NodeAdd(ANode: TXmlNode): integer;
begin
  if assigned(ANode) then
  begin
    ANode.Parent := Self;
    ANode.ChangeDocument(Document);
    if not assigned(FNodes) then
      FNodes := TList.Create;
    Result := FNodes.Add(ANode);
  end else
    Result := -1;
end;

function TXmlNode.NodeByAttributeValue(const NodeName, AttribName, AttribValue: UTF8String;
  ShouldRecurse: boolean): TXmlNode;
// This function returns a pointer to the first subnode that has an attribute with
// name AttribName and value AttribValue.
var
  i: integer;
  Node: TXmlNode;
begin
  Result := nil;
  // Find all nodes that are potential results
  for i := 0 to NodeCount - 1 do
  begin
    Node := Nodes[i];
    if (UTF8CompareText(Node.Name, NodeName) = 0) and
        Node.HasAttribute(AttribName) and
       (UTF8CompareText(Node.AttributeByName[AttribName], AttribValue) = 0) then
    begin
      Result := Node;
      exit;
    end;
    // Recursive call
    if ShouldRecurse then
      Result := Node.NodeByAttributeValue(NodeName, AttribName, AttribValue, True);
    if assigned(Result) then
      exit;
  end;
end;

function TXmlNode.NodeByElementType(ElementType: TXmlElementType): TXmlNode;
var
  i: integer;
begin
  Result := nil;
  for i := 0 to NodeCount - 1 do
    if Nodes[i].ElementType = ElementType then
    begin
      Result := Nodes[i];
      exit;
    end;
end;

function TXmlNode.NodeByName(const AName: UTF8String): TXmlNode;
var
  i: integer;
begin
  Result := nil;
  for i := 0 to NodeCount - 1 do
    if UTF8CompareText(Nodes[i].Name, AName) = 0 then
    begin
      Result := Nodes[i];
      exit;
    end;
end;

procedure TXmlNode.NodeDelete(Index: integer);
begin
  if (Index >= 0) and (Index < NodeCount) then
  begin
    TXmlNode(FNodes[Index]).Free;
    FNodes.Delete(Index);
  end;
end;

procedure TXmlNode.NodeExchange(Index1, Index2: integer);
begin
  if (Index1 >= 0) and (Index1 < Nodecount) and
     (Index2 >= 0) and (Index2 < Nodecount) then
    FNodes.Exchange(Index1, Index2);
end;

function TXmlNode.NodeExtract(ANode: TXmlNode): TXmlNode;
var
  Index: integer;
begin
  // Compatibility with Delphi4
  Result := nil;
  if assigned(FNodes) then
  begin
    Index := FNodes.IndexOf(ANode);
    if Index >= 0 then begin
      Result := ANode;
      FNodes.Delete(Index);
    end;
  end;
end;

function TXmlNode.NodeFindOrCreate(const AName: UTF8String): TXmlNode;
// Find the node with AName, and if not found, add new one
begin
  Result := NodeByName(AName);
  if not assigned(Result) then
    Result := NodeNew(AName);
end;

function TXmlNode.NodeIndexByName(const AName: UTF8String): integer;
begin
  Result := 0;
  while Result < NodeCount do
  begin
    if UTF8CompareText(Nodes[Result].Name, AName) = 0 then
      exit;
    inc(Result);
  end;
  if Result = NodeCount then
    Result := -1;
end;

function TXmlNode.NodeIndexByNameFrom(const AName: UTF8String; AFrom: integer): integer;
begin
  Result := AFrom;
  while Result < NodeCount do
  begin
    if UTF8CompareText(Nodes[Result].Name, AName) = 0 then
      exit;
    inc(Result);
  end;
  if Result = NodeCount then
    Result := -1;
end;

function TXmlNode.NodeIndexOf(ANode: TXmlNode): integer;
begin
  if assigned(ANode) and assigned(FNodes) then
    Result := FNodes.IndexOf(ANode)
  else
    Result := -1;
end;

procedure TXmlNode.NodeInsert(Index: integer; ANode: TXmlNode);
// Insert the node ANode at location Index in the list.
begin
  if not assigned(ANode) then
    exit;
  if (Index >=0) and (Index <= NodeCount) then
  begin
    if not assigned(FNodes) then
      FNodes := TList.Create;
    ANode.Parent := Self;
    FNodes.Insert(Index, ANode);
  end;
end;

function TXmlNode.NodeNew(const AName: UTF8String): TXmlNode;
// Add a new child node and return its pointer
begin
  Result := Nodes[NodeAdd(TXmlNode.CreateName(Document, AName))];
end;

function TXmlNode.NodeNewAtIndex(Index: integer; const AName: UTF8String): TXmlNode;
// Create a new node with AName, and insert it into the subnode list at location
// Index, and return a pointer to it.
begin
  if (Index >= 0) and (Index <= NodeCount) then
  begin
    Result := TXmlNode.CreateName(Document, AName);
    NodeInsert(Index, Result);
  end else
    Result := nil;
end;

function TXmlNode.NodeRemove(ANode: TxmlNode): integer;
begin
  Result := NodeIndexOf(ANode);
  if Result >= 0 then
    NodeDelete(Result);
end;

procedure TXmlNode.NodesByName(const AName: UTF8String; const AList: TList);
// Fill AList with nodes that have name AName
var
  i: integer;
begin
  if not assigned(AList) then
    exit;
  AList.Clear;
  for i := 0 to NodeCount - 1 do
    if UTF8CompareText(Nodes[i].Name, AName) = 0 then
      AList.Add(Nodes[i]);
end;

procedure TXmlNode.NodesClear;
var
  i: integer;
begin
  for i := 0 to NodeCount - 1 do
    TXmlNode(FNodes[i]).Free;
  FreeAndNil(FNodes);
end;

procedure TXmlNode.ParseTag(const AValue: UTF8String; TagStart, TagClose: integer);
var
  LItems: TsdUTF8StringList;
begin
  // Create a list to hold string items
  LItems := TsdUTF8StringList.Create;
  try
    sdUTF8ParseAttributes(AValue, TagStart, TagClose, LItems);

    // Determine name, attributes or value for each element type
    case ElementType of
    xeDeclaration:
      FName := 'xml';
    xeStyleSheet:
      begin
        FName := 'xml-stylesheet';
        // We also set this as the value for use in "StyleSheetString"
        ValueDirect := sdUTF8Trim(copy(AValue, TagStart, TagClose - TagStart));
      end;
    else
      // First item is the name - is it there?
      if LItems.Count = 0 then
        raise EFilerError.Create(sxeMissingElementName);

      // Set the name - using the element instead of property for speed
      FName := LItems[0];
      LItems.Delete(0);
    end;//case

    // Any attributes?
    if LItems.Count > 0 then
    begin
      CheckCreateAttributesList;
      FAttributes.Assign(LItems);
    end;

  finally
    LItems.Free;
  end;
end;

function TXmlNode.QualifyAsDirectNode: boolean;
// If this node qualifies as a direct node when writing, we return True.
// A direct node may have attributes, but no value or subnodes. Furhtermore,
// the root node will never be displayed as a direct node.
begin
  Result :=
    (Length(FValue) = 0) and
    (NodeCount = 0) and
    (ElementType = xeNormal) and
    not UseFullNodes and
    (TreeDepth > 0);
end;

function TXmlNode.ReadAttributeBool(const AName: UTF8String; ADefault: boolean): boolean;
var
  V: UTF8String;
begin
  Result := ADefault;
  V := AttributeByName[AName];
  if Length(V) = 0 then
    exit;

  try
    Result := sdStringToBool(V);
  except
    Result := ADefault;
  end;
end;

function TXmlNode.ReadAttributeDateTime(const AName: UTF8String; ADefault: TDateTime): TDateTime;
var
  V: UTF8String;
begin
  Result := ADefault;
  V := AttributeByName[AName];
  if Length(V) = 0 then
    exit;

  try
    Result := sdDateTimeFromStringDefault(V, ADefault, UseLocalBias);
  except
    Result := ADefault;
  end;
end;

function TXmlNode.ReadAttributeFloat(const AName: UTF8String; ADefault: double): double;
var
  V: UTF8String;
  Code: integer;
begin
  V := AttributeByName[AName];
  val(string(sdUTF8StringReplace(V, ',', '.')), Result, Code);
  if Code > 0 then
    Result := ADefault;
end;

function TXmlNode.ReadAttributeInteger(const AName: UTF8String; ADefault: integer): integer;
begin
  Result := StrToIntDef(string(AttributeByName[AName]), ADefault);
end;

function TXmlNode.ReadAttributeInt64(const AName: UTF8String; ADefault: int64): int64;
begin
  Result := StrToInt64Def(string(AttributeByName[AName]), ADefault);
end;

function TXmlNode.ReadAttributeString(const AName: UTF8String; const ADefault: UTF8String): UTF8String;
begin
  Result := AttributeByName[AName];
  if length(Result) = 0 then
    Result := ADefault;
end;

function TXmlNode.ReadBool(const AName: UTF8String; ADefault: boolean): boolean;
var
  Index: integer;
begin
  Result := ADefault;
  Index := NodeIndexByName(AName);
  if Index >= 0 then
    Result := Nodes[Index].ValueAsBoolDef(ADefault);
end;

{$IFDEF USEGRAPHICS}
procedure TXmlNode.ReadBrush(const AName: UTF8String; ABrush: TBrush);
var
  Child: TXmlNode;
begin
  Child := NodeByName(AName);
  if assigned(Child) then with Child do
  begin
    // Read values
    ABrush.Color  := ReadColor('Color', clWhite);
    ABrush.Style  := TBrushStyle(ReadInteger('Style', integer(bsSolid)));
  end else
  begin
    // Defaults
    ABrush.Bitmap := nil;
    ABrush.Color  := clWhite;
    ABrush.Style  := bsSolid;
  end;
end;

function TXmlNode.ReadColor(const AName: UTF8String; ADefault: TColor): TColor;
var
  Index: integer;
begin
  Result := ADefault;
  Index := NodeIndexByName(AName);
  if Index >= 0 then
    Result := StrToInt(string(Nodes[Index].ValueAsString));
end;
{$ENDIF}

function TXmlNode.ReadDateTime(const AName: UTF8String; ADefault: TDateTime): TDateTime;
// Date MUST always be written in this format:
// YYYY-MM-DD (if just date) or
// YYYY-MM-DDThh:mm:ss.sssZ (if date and time. The Z stands for universal time
// zone. Since Delphi's TDateTime does not give us a clue about the timezone,
// this is the easiest solution)
// This format SHOULD NOT be changed, to avoid all kinds of
// conversion errors in future.
// This format is compatible with the W3C date/time specification as found here:
// http://www.w3.org/TR/NOTE-datetime
begin
  Result := sdDateTimeFromStringDefault(ReadString(AName, ''), ADefault, UseLocalBias);
end;

function TXmlNode.ReadFloat(const AName: UTF8String; ADefault: double): double;
var
  Index: integer;
begin
  Result := ADefault;
  Index := NodeIndexByName(AName);
  if Index >= 0 then
    Result := Nodes[Index].ValueAsFloatDef(ADefault);
end;

{$IFDEF USEGRAPHICS}
procedure TXmlNode.ReadFont(const AName: UTF8String; AFont: TFont);
var
  Child: TXmlNode;
begin
  Child := NodeByName(AName);
  AFont.Style := [];
  if assigned(Child) then with Child do
  begin
    // Read values
    AFont.Name  := string(ReadString('Name', 'Arial'));
    AFont.Color := ReadColor('Color', clBlack);
    AFont.Size  := ReadInteger('Size', 14);
    if ReadBool('Bold', False)      then AFont.Style := AFont.Style + [fsBold];
    if ReadBool('Italic', False)    then AFont.Style := AFont.Style + [fsItalic];
    if ReadBool('Underline', False) then AFont.Style := AFont.Style + [fsUnderline];
    if ReadBool('Strikeout', False) then AFont.Style := AFont.Style + [fsStrikeout];
  end else
  begin
    // Defaults
    AFont.Name  := 'Arial';
    AFont.Color := clBlack;
    AFont.Size  := 14;
  end;
end;
{$ENDIF}

procedure TXmlNode.ReadFromStream(S: TStream);
// Read the node from the starting "<" until the closing ">" from the stream in S.
// This procedure also calls OnNodeNew and OnNodeLoaded events
var
  Ch: AnsiChar;
  i: integer;
  TagIndex: integer;
  V: UTF8String;
  Len: integer;
  Node: TXmlNode;
  NodeValue: UTF8String;
  ValuePos, ValueLen: integer;
  ClosePos: integer;
  HasCR: boolean;
  HasSubtags: boolean;
  Words: TsdUTF8StringList;
  IsDirect: boolean;
  Reader: TsdSurplusReader;
  // local
  procedure AddCharDataNode(PreserveWhiteSpace: boolean);
  var
    V: UTF8String;
    Node: TXmlNode;
    L: integer;
  begin
    // Add all text up till now as xeCharData
    if ValuePos > 0 then
    begin
      V := copy(NodeValue, 1, ValuePos);

      if PreserveWhiteSpace then
        L := length(V)
      else
        L := length(sdUTF8Trim(V));

      if L > 0 then
      begin
        Node := TXmlNode.CreateType(Document, xeCharData);
        Node.ValueDirect := V;
        NodeAdd(Node);
      end;
      ValuePos := 0;
    end;
  end;
// Main
begin
  // Check if we aborted parsing
  if AbortParsing then
    exit;
  // Clear this node first
  Clear;
  // Initial reserve textual value: just 80 AnsiCharacters which is OK for most short values
  ValuePos := 0;
  ValueLen := 80;
  SetLength(NodeValue, ValueLen);
  HasCR := False;
  HasSubTags := False;
  Reader := TsdSurplusReader.Create(S);
  try
    // Trailing blanks/controls AnsiChars?
    if not Reader.ReadCharSkipBlanks(Ch) then
      exit;

    // What is it?
    if Ch = '<' then
    begin
      // A tag - which one?
      TagIndex := ReadOpenTag(Reader);
      if TagIndex >= 0 then
      begin
        try
          ElementType := cTags[TagIndex].Style;
          case ElementType of
          xeNormal, xeDeclaration, xeStyleSheet:
            begin
              // These tags we will process
              ReadStringFromStreamUntil(Reader, cTags[TagIndex].Close, V, True);
              Len := length(V);

              // Is it a direct tag?
              IsDirect := False;
              if (ElementType = xeNormal) and (Len > 0) then
                if V[Len] = '/' then
                begin
                  dec(Len);
                  IsDirect := True;
                end;
              ParseTag(V, 1, Len + 1);

              // Here we know our name so good place to call OnNodeNew event
              if assigned(Document) then
              begin
                Document.DoNodeNew(Self);
                if AbortParsing then
                  exit;
              end;

              // Now the tag can be a direct close - in that case we're finished
              if IsDirect or (ElementType in [xeDeclaration, xeStyleSheet]) then
                exit;

              // Process rest of tag
              repeat

                // Read AnsiCharacter from stream
                if S.Read(Ch, 1) <> 1 then
                  raise EFilerError.CreateFmt(sxeMissingCloseTag, [Name]);

                // Is there a subtag?
                if Ch = '<' then
                begin
                  if not Reader.ReadCharSkipBlanks(Ch) then
                    raise EFilerError.CreateFmt(sxeMissingDataAfterGreaterThan, [Name]);
                  if Ch = '/' then
                  begin

                    // This seems our closing tag
                    if not ReadStringFromStreamUntil(Reader, '>', V, True) then
                      raise EFilerError.CreateFmt(sxeMissingLessThanInCloseTag, [Name]);
                    if UTF8CompareText(sdUTF8Trim(V), Name) <> 0 then
                      raise EFilerError.CreateFmt(sxeIncorrectCloseTag, [Name]);
                    V := '';
                    break;

                  end else
                  begin

                    // Add all text up till now as xeCharData
                    AddCharDataNode(False);

                    // Reset the HasCR flag if we add node, we only want to detect
                    // the CR after last subnode
                    HasCR := False;

                    // This is a subtag... so create it and let it process
                    HasSubTags := True;
                    S.Seek(-2, soCurrent);
                    Node := TXmlNode.Create(Document);
                    NodeAdd(Node);
                    Node.ReadFromStream(S);

                    // Check for dropping comments
                    if assigned(Document) and Document.DropCommentsOnParse and
                       (Node.ElementType = xeComment) then
                      NodeDelete(NodeIndexOf(Node));

                  end;
                end else
                begin

                  // If we detect a CR we will set the flag. This will signal the fact
                  // that this XML file was saved with xfReadable
                  if Ch = #13 then
                    HasCR := True;

                  // Add the AnsiCharacter to the node value buffer.
                  inc(ValuePos);
                  if ValuePos > ValueLen then
                  begin
                    inc(ValueLen, cNodeValueBuf);
                    SetLength(NodeValue, ValueLen);
                  end;
                  NodeValue[ValuePos] := Ch;

                end;
              until False or AbortParsing;

              // Add all text up till now as xeText
              AddCharDataNode(not HasSubtags);

              // Check AnsiCharData nodes, remove trailing CRLF + indentation if we
              // were in xfReadable mode
              if HasSubtags and HasCR then
              begin
                for i := 0 to NodeCount - 1 do
                  if Nodes[i].ElementType = xeCharData then
                  begin
                    ClosePos := length(Nodes[i].FValue);
                    while (ClosePos > 0) and (Nodes[i].FValue[ClosePos] in [#10, #13, ' ']) do
                      dec(ClosePos);
                    Nodes[i].FValue := copy(Nodes[i].FValue, 1, ClosePos);
                  end;
              end;

              // If the first node is xeCharData we use it as ValueDirect
              if NodeCount > 0 then
                if Nodes[0].ElementType = xeCharData then
                begin
                  ValueDirect := Nodes[0].ValueDirect;
                  NodeDelete(0);
                end;

            end;
          xeDocType:
            begin
              Name := 'DTD';
              if assigned(Document) then
              begin
                Document.DoNodeNew(Self);
                if AbortParsing then
                  exit;
              end;
              // Parse DTD
              if assigned(Document) then
                Document.ParseDTD(Self, S);
            end;
          xeElement, xeAttList, xeEntity, xeNotation:
            begin
              // DTD elements
              ReadStringFromStreamWithQuotes(S, cTags[TagIndex].Close, V);
              Len := length(V);
              Words := TsdUTF8StringList.Create;
              try
                sdUTF8ParseAttributes(V, 1, Len + 1, Words);
                if Words.Count > 0 then
                begin
                  Name := Words[0];
                  Words.Delete(0);
                end;
                ValueDirect := sdUTF8Trim(Words.Text);
              finally
                Words.Free;
              end;
              if assigned(Document) then
              begin
                Document.DoNodeNew(Self);
                if AbortParsing then
                  exit;
              end;
            end;
          else
            case ElementType of
            xeComment:  Name := 'Comment';
            xeCData:    Name := 'CData';
            xeExclam:   Name := 'Special';
            xeQuestion: Name := 'Special';
            else
              Name := 'Unknown';
            end; //case

            // Here we know our name so good place to call OnNodeNew
            if assigned(Document) then
            begin
              Document.DoNodeNew(Self);
              if AbortParsing then
                exit;
            end;

            // In these cases just get all data up till the closing tag
            ReadStringFromStreamUntil(Reader, cTags[TagIndex].Close, V, False);
            ValueDirect := V;
          end;//case
        finally
          // Call the OnNodeLoaded and OnProgress events
          if assigned(Document) and not AbortParsing then
          begin
            Document.DoProgress(S.Position);
            Document.DoNodeLoaded(Self);
          end;
        end;
      end;
    end else if True then begin
      raise EFilerError.CreateFmt(sxeErrorUnexpectedChar, ['<']);
    end;
  finally
    Reader.Free;
  end;
end;

procedure TXmlNode.ReadFromString(const AValue: UTF8String);
var
  S: TStream;
begin
  S := TsdUTF8StringStream.Create(AValue);
  try
    ReadFromStream(S);
  finally
    S.Free;
  end;
end;

function TXmlNode.ReadInt64(const AName: UTF8String; ADefault: int64): int64;
var
  Index: integer;
begin
  Result := ADefault;
  Index := NodeIndexByName(AName);
  if Index >= 0 then
    Result := Nodes[Index].ValueAsInt64Def(ADefault);
end;

function TXmlNode.ReadInteger(const AName: UTF8String; ADefault: integer): integer;
var
  Index: integer;
begin
  Result := ADefault;
  Index := NodeIndexByName(AName);
  if Index >= 0 then
    Result := Nodes[Index].ValueAsIntegerDef(ADefault);
end;

{$IFDEF USEGRAPHICS}
procedure TXmlNode.ReadPen(const AName: UTF8String; APen: TPen);
var
  Child: TXmlNode;
begin
  Child := NodeByName(AName);
  if assigned(Child) then with Child do
  begin
    // Read values
    APen.Color := ReadColor('Color', clBlack);
    APen.Mode  := TPenMode(ReadInteger('Mode', integer(pmCopy)));
    APen.Style := TPenStyle(ReadInteger('Style', integer(psSolid)));
    APen.Width := ReadInteger('Width', 1);
  end else
  begin
    // Defaults
    APen.Color := clBlack;
    APen.Mode := pmCopy;
    APen.Style := psSolid;
    APen.Width := 1;
  end;
end;
{$ENDIF}

function TXmlNode.ReadString(const AName: UTF8String; const ADefault: UTF8String): UTF8String;
var
  Index: integer;
begin
  Result := ADefault;
  Index := NodeIndexByName(AName);
  if Index >= 0 then
    Result := Nodes[Index].ValueAsString;
end;

function TXmlNode.ReadUnicodeString(const AName: UTF8String; const ADefault: UnicodeString): UnicodeString;
begin
  Result := ToUnicodeString(ReadString(AName, FromUnicodeString(ADefault)));
end;

procedure TXmlNode.ResolveEntityReferences;
// Replace any entity references by the entities, and parse the new content if any
  // local
  function SplitReference(const AValue: UTF8String; var Text1, Text2: UTF8String): UTF8String;
  var
    P: integer;
  begin
    Result := '';
    P := UTF8Pos('&', AValue);
    Text1 := '';
    Text2 := AValue;
    if P = 0 then
      exit;
    Text1 := copy(AValue, 1, P - 1);
    Text2 := copy(AValue, P + 1, length(AValue));
    P := UTF8Pos(';', Text2);
    if P = 0 then
      exit;
    Result := copy(Text2, 1, P - 1);
    Text2 := copy(Text2, P + 1, length(Text2));
  end;
  // local
  function ReplaceEntityReferenceByNodes(ARoot: TXmlNode; const AValue: UTF8String; var InsertPos: integer; var Text1, Text2: UTF8String): boolean;
  var
    Reference: UTF8String;
    Entity: UTF8String;
    Node: TXmlNode;
    S: TStream;
  begin
    Result := False;
    Reference := SplitReference(AValue, Text1, Text2);
    if (length(Reference) = 0) or not assigned(Document) then
      exit;

    // Lookup entity references
    Entity := Document.EntityByName[Reference];

    // Does the entity contain markup?
    if (length(Entity) > 0) and (UTF8Pos('<', Entity) > 0) then
    begin
      S := TsdUTF8StringStream.Create(Entity);
      try
        while S.Position < S.Size do
        begin
          Node := TXmlNode.Create(Document);
          Node.ReadFromStream(S);
          if Node.IsEmpty then
            Node.Free
          else
          begin
            ARoot.NodeInsert(InsertPos, Node);
            inc(InsertPos);
            Result := True;
          end;
        end;
      finally
        S.Free;
      end;
    end;
  end;
// main
var
  i: integer;
  InsertPos: integer;
  Text1, Text2: UTF8String;
  Node: TXmlNode;
  V, Reference, Replace, Entity, First, Last: UTF8String;
begin
  if length(FValue) > 0 then
  begin
    // Different behaviour for xeNormal and xeCharData
    if ElementType = xeNormal then
    begin
      InsertPos := 0;
      if ReplaceEntityReferenceByNodes(Self, FValue, InsertPos, Text1, Text2) then
      begin
        FValue := Text1;
        if length(sdUTF8Trim(Text2)) > 0 then
        begin
          Node := TXmlNode.CreateType(Document, xeCharData);
          Node.ValueDirect := Text2;
          NodeInsert(InsertPos, Node);
        end;
      end;
    end else if (ElementType = xeCharData) and assigned(Parent) then
    begin
      InsertPos := Parent.NodeIndexOf(Self);
      if ReplaceEntityReferenceByNodes(Parent, FValue, InsertPos, Text1, Text2) then
      begin
        FValue := Text1;
        if length(sdUTF8Trim(FValue)) = 0 then
          FValue := '';
        if length(sdUTF8Trim(Text2)) > 0 then
        begin
          Node := TXmlNode.CreateType(Document, xeCharData);
          Node.ValueDirect := Text2;
          Parent.NodeInsert(InsertPos, Node);
        end;
      end;
    end;
  end;

  // Do attributes
  for i := 0 to AttributeCount - 1 do
  begin
    Last := AttributeValue[i];
    V := '';
    repeat
      Reference := SplitReference(Last, First, Last);
      Replace := '';
      if length(Reference) > 0 then
      begin
        Entity := Document.EntityByName[Reference];
        if length(Entity) > 0 then
           Replace := Entity
        else
          Replace := '&' + Reference + ';';
      end;
      V := V + First + Replace;
    until length(Reference) = 0;
    V := V + Last;
    AttributeValue[i] := V;
  end;

  // Do childnodes too
  i := 0;
  while i < NodeCount do
  begin
    Nodes[i].ResolveEntityReferences;
    inc(i);
  end;

  // Check for empty AnsiCharData nodes
  for i := NodeCount - 1 downto 0 do
    if (Nodes[i].ElementType = xeCharData) and (length(Nodes[i].ValueDirect) = 0) then
      NodeDelete(i);
end;

procedure TXmlNode.SetAttributeByName(const AName, Value: UTF8String);
begin
  CheckCreateAttributesList;
  FAttributes.Values[AName] := sdUTF8QuotedString(sdUTF8EscapeString(Value));
end;

procedure TXmlNode.SetAttributeByNameWide(const AName: UTF8String; const Value: UnicodeString);
begin
  SetAttributeByName(AName, FromUnicodeString(Value));
end;

procedure TXmlNode.SetAttributeName(Index: integer; const Value: UTF8String);
var
  S: UTF8String;
  P: integer;
begin
  if (Index >= 0) and (Index < AttributeCount) then
  begin
    S := FAttributes[Index];
    P := Utf8Pos('=', S);
    if P > 0 then
      FAttributes[Index] := Value + '=' + Copy(S, P + 1, MaxInt);
  end;
end;

procedure TXmlNode.SetAttributeValue(Index: integer; const Value: UTF8String);
begin
  if (Index >= 0) and (Index < AttributeCount) then
    FAttributes[Index] := AttributeName[Index] + '=' +
      sdUTF8QuotedString(sdUTF8EscapeString(Value));
end;

procedure TXmlNode.SetAttributeValueAsInteger(Index: integer; const Value: integer);
begin
  SetAttributeValue(Index, IntToUTF8Str(Value));
end;

procedure TXmlNode.SetAttributeValueAsUnicodeString(Index: integer;
  const Value: UnicodeString);
begin
  SetAttributeValue(Index, FromUnicodeString(Value));
end;

procedure TXmlNode.SetAttributeValueDirect(Index: integer; const Value: UTF8String);
begin
  if (Index >= 0) and (Index < AttributeCount) then
    FAttributes[Index] := AttributeName[Index] + '=' +
      sdUTF8QuotedString(Value);
end;

procedure TXmlNode.SetBinaryEncoding(const Value: TBinaryEncodingType);
begin
  if assigned(Document) then
    Document.BinaryEncoding := Value;
end;

procedure TXmlNode.SetBinaryString(const Value: RawByteString);
var
  OldEncoding: TBinaryEncodingType;
begin
  // Set to base64
  OldEncoding := BinaryEncoding;
  try
    BinaryEncoding := xbeBase64;
    if length(Value) = 0 then
    begin
      ValueAsString := '';
      exit;
    end;
    // fill the buffer
    {$IFDEF CLR}
    BufferWrite(BytesOf(Value), length(Value));
    {$ELSE}
    BufferWrite(Value[1], length(Value));
    {$ENDIF}
  finally
    BinaryEncoding := OldEncoding;
  end;
end;

procedure TXmlNode.SetName(const Value: UTF8String);
var
  i: integer;
begin
  if FName <> Value then
  begin
    // Check if the name abides the rules. We will be very forgiving here and
    // just accept any name that at least does not contain control AnsiCharacters
    for i := 1 to length(Value) do
      if Value[i] in cControlChars then
        raise Exception.Create(Format(sxeIllegalCharInNodeName, [Value]));
    FName := Value;
  end;
end;

procedure TXmlNode.SetValueAsBool(const Value: boolean);
begin
  FValue := sdStringFromBool(Value);
end;

procedure TXmlNode.SetValueAsDateTime(const Value: TDateTime);
begin
  ValueAsString := sdDateTimeToString(Value, UseLocalBias);
end;

procedure TXmlNode.SetValueAsFloat(const Value: double);
begin
  FValue := sdWriteNumber(Value, FloatSignificantDigits, FloatAllowScientific);
end;

procedure TXmlNode.SetValueAsInt64(const Value: int64);
begin
  FValue := Int64ToUTF8Str(Value);
end;

procedure TXmlNode.SetValueAsInteger(const Value: integer);
begin
  FValue := IntToUTF8Str(Value);
end;

procedure TXmlNode.SetValueAsString(const AValue: UTF8String);
begin
  FValue := sdUTF8EscapeString(AValue);
end;

procedure TXmlNode.SetValueAsUnicodeString(const Value: UnicodeString);
begin
  ValueAsString := FromUnicodeString(Value);
end;

procedure TXmlNode.SortChildNodes(Compare: TXMLNodeCompareFunction; Info: TPointer);
// Sort the child nodes using the quicksort algorithm
  //local
  function DoNodeCompare(Node1, Node2: TXmlNode): integer;
  begin
    if assigned(Compare) then
      Result := Compare(Node1, Node2, Info)
    else
      if assigned(Document) and assigned(Document.OnNodeCompare) then
        Result := Document.OnNodeCompare(Document, Node1, Node2, Info)
      else
        Result := UTF8CompareText(Node1.Name, Node2.Name);
  end;
  // local
  procedure QuickSort(iLo, iHi: Integer);
  var
    Lo, Hi, Mid: longint;
  begin
    Lo := iLo;
    Hi := iHi;
    Mid:= (Lo + Hi) div 2;
    repeat
      while DoNodeCompare(Nodes[Lo], Nodes[Mid]) < 0 do
        Inc(Lo);
      while DoNodeCompare(Nodes[Hi], Nodes[Mid]) > 0 do
        Dec(Hi);
      if Lo <= Hi then
      begin
        // Swap pointers;
        NodeExchange(Lo, Hi);
        if Mid = Lo then
          Mid := Hi
        else
          if Mid = Hi then
            Mid := Lo;
        Inc(Lo);
        Dec(Hi);
      end;
    until Lo > Hi;
    if Hi > iLo then
      QuickSort(iLo, Hi);
    if Lo < iHi then
      QuickSort(Lo, iHi);
  end;
// main
begin
  if NodeCount > 1 then
    QuickSort(0, NodeCount - 1);
end;

function TXmlNode.ToUnicodeString(const s: UTF8String): UnicodeString;
begin
  Result := sdUtf8ToUnicode(s)
end;

function TXmlNode.UnescapeString(const AValue: UTF8String): UTF8String;
begin
  Result := sdUTF8UnEscapeString(AValue)
end;

function TXmlNode.UseFullNodes: boolean;
begin
  Result := False;
  if assigned(Document) then
    Result := Document.UseFullNodes;
end;

function TXmlNode.UseLocalBias: Boolean;
begin
  Result := False;
  if Assigned(Document) then
    Result := Document.UseLocalBias;
end;

function TXmlNode.ValueAsBoolDef(ADefault: boolean): boolean;
var
  Ch: AnsiChar;
begin
  Result := ADefault;
  if Length(FValue) = 0 then
    exit;
  Ch := sdUpCase(FValue[1]);
  if Ch in ['T', 'Y', '1'] then
  begin
    Result := True;
    exit;
  end;
  if Ch in ['F', 'N', '0'] then
  begin
    Result := False;
    exit;
  end;
end;

function TXmlNode.ValueAsDateTimeDef(ADefault: TDateTime): TDateTime;
begin
  Result := sdDateTimeFromStringDefault(ValueAsString, ADefault, UseLocalBias);
end;

function TXmlNode.ValueAsFloatDef(ADefault: double): double;
var
  Code: integer;
begin
  try
    val(string(sdUTF8StringReplace(FValue, ',', '.')), Result, Code);
    if Code > 0 then
      Result := ADefault;
  except
    Result := ADefault;
  end;
end;

function TXmlNode.ValueAsInt64Def(ADefault: int64): int64;
begin
  Result := StrToInt64Def(string(FValue), ADefault);
end;

function TXmlNode.ValueAsIntegerDef(ADefault: integer): integer;
begin
  Result := StrToIntDef(string(FValue), ADefault);
end;

procedure TXmlNode.WriteAttributeBool(const AName: UTF8String; AValue: boolean; ADefault: boolean);
var
  Index: integer;
begin
  if WriteOnDefault or (AValue <> ADefault) then
  begin
    Index := AttributeIndexByName(AName);
    if Index >= 0 then
      AttributeValue[Index] := sdStringFromBool(AValue)
    else
      AttributeAdd(AName, sdStringFromBool(AValue));
  end;
end;

procedure TXmlNode.WriteAttributeDateTime(const AName: UTF8String; AValue, ADefault: TDateTime);
var
  Index: integer;
begin
  if WriteOnDefault or (AValue <> ADefault) then
  begin
    Index := AttributeIndexByName(AName);
    if Index >= 0 then
      AttributeValue[Index] := sdDateTimeToString(AValue, UseLocalBias)
    else
      AttributeAdd(AName, sdDateTimeToString(AValue, UseLocalBias));
  end;
end;

procedure TXmlNode.WriteAttributeFloat(const AName: UTF8String; AValue, ADefault: double);
var
  Index: integer;
  S: UTF8String;
begin
  if WriteOnDefault or (AValue <> ADefault) then
  begin
    Index := AttributeIndexByName(AName);
    S := sdWriteNumber(AValue, FloatSignificantDigits, FloatAllowScientific);
    if Index >= 0 then
      AttributeValue[Index] := S
    else
      AttributeAdd(AName, S);
  end;
end;

procedure TXmlNode.WriteAttributeInteger(const AName: UTF8String; AValue: integer; ADefault: integer);
var
  Index: integer;
begin
  if WriteOnDefault or (AValue <> ADefault) then
  begin
    Index := AttributeIndexByName(AName);
    if Index >= 0 then
      AttributeValue[Index] := IntToUTF8Str(AValue)
    else
      AttributeAdd(AName, IntToUTF8Str(AValue));
  end;
end;

procedure TXmlNode.WriteAttributeInt64(const AName: UTF8String; const AValue: int64; ADefault: int64);
var
  Index: integer;
begin
  if WriteOnDefault or (AValue <> ADefault) then
  begin
    Index := AttributeIndexByName(AName);
    if Index >= 0 then
      AttributeValue[Index] := IntToUTF8Str(AValue)
    else
      AttributeAdd(AName, IntToUTF8Str(AValue));
  end;
end;

procedure TXmlNode.WriteAttributeString(const AName, AValue, ADefault: UTF8String);
var
  Index: integer;
begin
  if WriteOnDefault or (AValue <> ADefault) then
  begin
    Index := AttributeIndexByName(AName);
    if Index >= 0 then
      AttributeValue[Index] := AValue
    else
      AttributeAdd(AName, AValue);
  end;
end;

procedure TXmlNode.WriteBool(const AName: UTF8String; AValue: boolean; ADefault: boolean);
const
  cBoolValues: array[boolean] of UTF8String = ('False', 'True');
begin
  if WriteOnDefault or (AValue <> ADefault) then
    with NodeFindOrCreate(AName) do
      ValueAsString := cBoolValues[AValue];
end;

{$IFDEF USEGRAPHICS}
procedure TXmlNode.WriteBrush(const AName: UTF8String; ABrush: TBrush);
begin
  with NodeFindOrCreate(AName) do
  begin
    WriteColor('Color', ABrush.Color, clBlack);
    WriteInteger('Style', integer(ABrush.Style), 0);
  end;
end;

procedure TXmlNode.WriteColor(const AName: UTF8String; AValue, ADefault: TColor);
begin
  if WriteOnDefault or (AValue <> ADefault) then
    WriteHex(AName, ColorToRGB(AValue), 8, 0);
end;
{$ENDIF}

procedure TXmlNode.WriteDateTime(const AName: UTF8String; AValue, ADefault: TDateTime);
// Date MUST always be written in this format:
// YYYY-MM-DD (if just date) or
// YYYY-MM-DDThh:mm:ss.sssZ (if date and time. The Z stands for universal time
// zone. Since Delphi's TDateTime does not give us a clue about the timezone,
// this is the easiest solution)
// This format SHOULD NOT be changed, to avoid all kinds of
// conversion errors in future.
// This format is compatible with the W3C date/time specification as found here:
// http://www.w3.org/TR/NOTE-datetime
begin
  if WriteOnDefault or (AValue <> ADefault) then
    WriteString(AName, sdDateTimeToString(AValue, UseLocalBias), '');
end;

procedure TXmlNode.WriteFloat(const AName: UTF8String; AValue: double; ADefault: double);
begin
  if WriteOnDefault or (AValue <> ADefault) then
    with NodeFindOrCreate(AName) do
      ValueAsString := sdWriteNumber(AValue, FloatSignificantDigits, FloatAllowScientific);
end;

{$IFDEF USEGRAPHICS}
procedure TXmlNode.WriteFont(const AName: UTF8String; AFont: TFont);
begin
  with NodeFindOrCreate(AName) do
  begin
    WriteString('Name', UTF8String(AFont.Name), 'Arial');
    WriteColor('Color', AFont.Color, clBlack);
    WriteInteger('Size', AFont.Size, 14);
    WriteBool('Bold', fsBold in AFont.Style, False);
    WriteBool('Italic', fsItalic in AFont.Style, False);
    WriteBool('Underline', fsUnderline in AFont.Style, False);
    WriteBool('Strikeout', fsStrikeout in AFont.Style, False);
  end;
end;
{$ENDIF}

procedure TXmlNode.WriteHex(const AName: UTF8String; AValue, Digits: integer; ADefault: integer);
begin
  if WriteOnDefault or (AValue <> ADefault) then
    with NodeFindOrCreate(AName) do
      ValueAsString := '$' + UTF8String(IntToHex(AValue, Digits));
end;

function TXmlNode.WriteInnerTag: UTF8String;
// Write the inner part of the tag, the one that contains the attributes
var
  i: integer;
begin
  Result := '';
  // Attributes
  for i := 0 to AttributeCount - 1 do
    // Here we used to prevent empty attributes, but in fact, empty attributes
    // should be allowed because sometimes they're required
    Result := Result + ' ' + AttributePair[i];
  // End of tag - direct nodes get an extra "/"
  if QualifyAsDirectNode then
    Result := Result + '/';
end;

procedure TXmlNode.WriteInt64(const AName: UTF8String; AValue, ADefault: int64);
begin
  if WriteOnDefault or (AValue <> ADefault) then
    with NodeFindOrCreate(AName) do
      ValueAsString := IntToUTF8Str(AValue);
end;

procedure TXmlNode.WriteInteger(const AName: UTF8String; AValue: integer; ADefault: integer);
begin
  if WriteOnDefault or (AValue <> ADefault) then
    with NodeFindOrCreate(AName) do
      ValueAsString := IntToUTF8Str(AValue);
end;

{$IFDEF USEGRAPHICS}
procedure TXmlNode.WritePen(const AName: UTF8String; APen: TPen);
begin
  with NodeFindOrCreate(AName) do
  begin
    WriteColor('Color', APen.Color, clBlack);
    WriteInteger('Mode', integer(APen.Mode), 0);
    WriteInteger('Style', integer(APen.Style), 0);
    WriteInteger('Width', APen.Width, 0);
  end;
end;
{$ENDIF}

procedure TXmlNode.WriteString(const AName, AValue: UTF8String; const ADefault: UTF8String);
begin
  if WriteOnDefault or (AValue <> ADefault) then
    with NodeFindOrCreate(AName) do
      ValueAsString := AValue;
end;

procedure TXmlNode.WriteToStream(S: TStream);
var
  i: integer;
  Indent: UTF8String;
  LFeed: UTF8String;
  Line: UTF8String;
  ThisNode, NextNode: TXmlNode;
  AddLineFeed: boolean;
begin
  Indent := GetIndent;
  LFeed := GetLineFeed;

  // Write indent
  Line := Indent;

  // Write the node - distinguish node type
  case ElementType of
  xeDeclaration: // XML declaration <?xml{declaration}?>
    begin
      // Explicitly delete empty attributes in the declaration,
      // this is usually the encoding and we do not want encoding=""
      // to show up
      DeleteEmptyAttributes;
      Line := Indent + '<?xml' + WriteInnerTag + '?>';
    end;
  xeStylesheet: // Stylesheet <?xml-stylesheet{stylesheet}?>
    Line := Indent + '<?xml-stylesheet' + WriteInnerTag + '?>';
  xeDoctype:
    begin
      if NodeCount = 0 then
        Line := Indent + '<!DOCTYPE ' + Name + ' ' + ValueDirect + '>'
      else
      begin
        Line := Indent + '<!DOCTYPE ' + Name + ' ' + ValueDirect + ' [' + LFeed;
        sdUTF8WriteStringToStream(S, Line);
        for i := 0 to NodeCount - 1 do
        begin
          Nodes[i].WriteToStream(S);
          sdUTF8WriteStringToStream(S, LFeed);
        end;
        Line := ']>';
      end;
    end;
  xeElement:
    Line := Indent + '<!ELEMENT ' + Name + ' ' + ValueDirect + '>';
  xeAttList:
    Line := Indent + '<!ATTLIST ' + Name + ' ' + ValueDirect + '>';
  xeEntity:
    Line := Indent + '<!ENTITY ' + Name + ' ' + ValueDirect + '>';
  xeNotation:
    Line := Indent + '<!NOTATION ' + Name + ' ' + ValueDirect + '>';
  xeComment: // Comment <!--{comment}-->
    Line := Indent + '<!--' + ValueDirect + '-->';
  xeCData: // literal data <![CDATA[{data}]]>
    Line := Indent + '<![CDATA[' + ValueDirect + ']]>';
  xeExclam: // Any <!data>
    Line := Indent + '<!' + ValueDirect + '>';
  xeQuestion: // Any <?data?>
    Line := Indent + '<?' + ValueDirect + '?>';
  xeCharData:
    Line := FValue;
  xeUnknown: // Any <data>
    Line := Indent + '<' + ValueDirect + '>';
  xeNormal: // normal nodes (xeNormal)
    begin
      // Write tag
      Line := Line + '<' + FName + WriteInnerTag + '>';

      // Write value (if any)
      Line := Line + FValue;
      if (NodeCount > 0) then
        // ..and a linefeed
        Line := Line + LFeed;

      sdUTF8WriteStringToStream(S, Line);

      // Write child elements
      for i := 0 to NodeCount - 1 do
      begin
        ThisNode := Nodes[i];
        NextNode := Nodes[i + 1];
        ThisNode.WriteToStream(S);
        AddLineFeed := True;
        if ThisNode.ElementType = xeCharData then
          AddLineFeed := False;
        if assigned(NextNode) then
          if NextNode.ElementType = xeCharData then
            AddLineFeed := False;
        if AddLineFeed then
          sdUTF8WriteStringToStream(S, LFeed);
      end;

      // Write end tag
      Line := '';
      if not QualifyAsDirectNode then
      begin
        if NodeCount > 0 then
          Line := Indent;
        Line := Line + '</' + FName + '>';
      end;
    end;
  else
    raise EFilerError.Create(sxeIllegalElementType);
  end;//case
  sdUTF8WriteStringToStream(S, Line);

  // Call the onprogress
  if assigned(Document) then
    Document.DoProgress(S.Position);
end;

function TXmlNode.WriteToString: UTF8String;
var
  S: TsdUTF8StringStream;
begin
  // We will simply call WriteToStream and collect the result as UTF8String using
  // a string stream
  S := TsdUTF8StringStream.Create('');
  try
    WriteToStream(S);
    Result := S.DataString;
  finally
    S.Free;
  end;
end;

procedure TXmlNode.WriteUnicodeString(const AName: UTF8String;
  const AValue: UnicodeString; const ADefault: UnicodeString);
begin
  WriteString(AName, FromUnicodeString(AValue), FromUnicodeString(ADefault));
end;

{ TXmlNodeList }

function TXmlNodeList.ByAttribute(const AName, AValue: UTF8String): TXmlNode;
var
  i: integer;
begin
  for i := 0 to Count - 1 do
    if UTF8CompareText(Items[i].AttributeByName[AName], AValue) = 0 then
    begin
      Result := Items[i];
      exit;
    end;
  Result := nil;
end;

function TXmlNodeList.GetItems(Index: Integer): TXmlNode;
begin
  Result := TXmlNode(Get(Index));
end;

procedure TXmlNodeList.SetItems(Index: Integer; const Value: TXmlNode);
begin
  Put(Index, TPointer(Value));
end;

{ TNativeXml }

procedure TNativeXml.Assign(Source: TPersistent);
  // local
  procedure SetDocumentRecursively(ANode: TXmlNode; ADocument: TNativeXml);
  var
    i: integer;
  begin
    ANode.Document := ADocument;
    for i := 0 to ANode.NodeCount - 1 do
      SetDocumentRecursively(ANode.Nodes[i], ADocument);
  end;
// main
begin
  if Source is TNativeXml then
  begin
    // Copy private members
    FBinaryEncoding := TNativeXml(Source).FBinaryEncoding;
    FDropCommentsOnParse := TNativeXml(Source).FDropCommentsOnParse;
    FExternalEncoding := TNativeXml(Source).FExternalEncoding;
    FParserWarnings := TNativeXml(Source).FParserWarnings;
    FIndentString := TNativeXml(Source).FIndentString;
    FUseFullNodes := TNativeXml(Source).FUseFullNodes;
    FUseLocalBias := TNativeXml(Source).FUseLocalBias;
    FWriteOnDefault := TNativeXml(Source).FWriteOnDefault;
    FXmlFormat := TNativeXml(Source).FXmlFormat;
    // Assign root
    FRootNodes.Assign(TNativeXml(Source).FRootNodes);
    // Set Document property recursively
    SetDocumentRecursively(FRootNodes, Self);
  end else
    if Source is TXmlNode then
    begin
      // Assign this node to the FRootNodes property
      FRootNodes.Assign(Source);
      // Set Document property recursively
      SetDocumentRecursively(FRootNodes, Self);
    end else
      inherited;
end;

procedure TNativeXml.Clear;
var
  Node: TXmlNode;
begin
  // Reset defaults
  SetDefaults;
  // Clear root
  FRootNodes.Clear;
  // Build default items in RootNodes
  // - first the declaration
  Node := TXmlNode.CreateType(Self, xeDeclaration);
  Node.Name := 'xml';
  Node.AttributeAdd('version', cDefaultVersionString);
  Node.AttributeAdd('encoding', cDefaultEncodingString);
  FRootNodes.NodeAdd(Node);
  // - then the root node
  FRootNodes.NodeNew('');
end;

procedure TNativeXml.CopyFrom(Source: TNativeXml);
begin
  if not assigned(Source) then
    exit;
  Assign(Source);
end;

constructor TNativeXml.Create;
begin
  inherited Create;
  FRootNodes := TXmlNode.Create(Self);
  Clear;
end;

constructor TNativeXml.CreateName(const ARootName: UTF8String);
begin
  Create;
  Root.Name := ARootName;
end;

destructor TNativeXml.Destroy;
begin
  FreeAndNil(FRootNodes);
  inherited;
end;

procedure TNativeXml.DoNodeLoaded(Node: TXmlNode);
begin
  if assigned(FOnNodeLoaded) then
    FOnNodeLoaded(Self, Node);
end;

procedure TNativeXml.DoNodeNew(Node: TXmlNode);
begin
  if assigned(FOnNodeNew) then
    FOnNodeNew(Self, Node);
end;

procedure TNativeXml.DoProgress(Size: integer);
begin
  if assigned(FOnProgress) then
    FOnProgress(Self, Size);
end;

procedure TNativeXml.DoUnicodeLoss(Sender: TObject);
begin
  if assigned(FOnUnicodeLoss) then
    FOnUnicodeLoss(Self);
end;

function TNativeXml.GetCommentString: UTF8String;
// Get the first comment node, and return its value
var
  Node: TXmlNode;
begin
  Result := '';
  Node := FRootNodes.NodeByElementType(xeComment);
  if assigned(Node) then
    Result := Node.ValueAsString;
end;

function TNativeXml.GetEncodingString: UTF8String;
begin
  Result := '';
  if FRootNodes.NodeCount > 0 then
    if FRootNodes[0].ElementType = xeDeclaration then
      Result := FRootNodes[0].AttributeByName['encoding'];
end;

function TNativeXml.GetEntityByName(AName: UTF8String): UTF8String;
var
  i, j: integer;
begin
  Result := '';
  for i := 0 to FRootNodes.NodeCount - 1 do
    if FRootNodes[i].ElementType = xeDoctype then with FRootNodes[i] do
    begin
      for j := 0 to NodeCount - 1 do
        if (Nodes[j].ElementType = xeEntity) and (Nodes[j].Name = AName) then
        begin
          Result := sdUTF8UnQuotedString(sdUTF8Trim(Nodes[j].ValueDirect));
          exit;
        end;
    end;
end;

function TNativeXml.GetRoot: TXmlNode;
begin
  Result := FRootNodes.NodeByElementType(xeNormal);
end;

function TNativeXml.GetStyleSheetNode: TXmlNode;
begin
  Result := FRootNodes.NodeByElementType(xeStylesheet);
  if not assigned(Result) then
  begin
    // Add a stylesheet node as second one if none present
    Result := TXmlNode.CreateType(Self, xeStyleSheet);
    FRootNodes.NodeInsert(1, Result);
  end;
end;

function TNativeXml.GetUtf8Encoded: boolean;
begin
  Result := True;
end;

function TNativeXml.GetVersionString: UTF8String;
begin
  Result := '';
  if FRootNodes.NodeCount > 0 then
    if FRootNodes[0].ElementType = xeDeclaration then
      Result := FRootNodes[0].AttributeByName['version'];
end;

function TNativeXml.IsEmpty: boolean;
var
  R: TXmlNode;
begin
  Result := True;
  R := GetRoot;
  if assigned(R) then
    Result := R.IsClear;
end;

function TNativeXml.LineFeed: UTF8String;
begin
  case XmlFormat of
  xfReadable:
    Result := #13#10;
  xfCompact:
    Result := #10;
  else
    Result := #10;
  end;//case
end;

procedure TNativeXml.LoadFromFile(const AFileName: string);
var
  S: TStream;
begin
  S := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite);
  try
    LoadFromStream(S);
  finally
    S.Free;
  end;
end;

procedure TNativeXml.LoadFromStream(Stream: TStream);
var
  B: TsdBufferedReadStream;
begin
  // Create buffer filter. Since we read from the original stream a buffer at a
  // time, this speeds up the reading process for disk-based files.
  B := TsdBufferedReadStream.Create(Stream, False);
  try
    // We will create a conversion stream as intermediate
    FCodecStream := TsdUtf8Stream.Create(B);
    try
      // Connect events
      FCodecStream.OnUnicodeLoss := DoUnicodeLoss;
      // Read from stream
      ReadFromStream(FCodecStream);
      // Set our external encoding
      FExternalEncoding := FCodecStream.Encoding;
    finally
      FreeAndNil(FCodecStream);
    end;
  finally
    B.Free;
  end;
end;

procedure TNativeXml.ParseDTD(ANode: TXmlNode; S: TStream);
// DTD parsing is quite different from normal node parsing so it is brought
// under in the main NativeXml object
  // local
  procedure ParseMarkupDeclarations;
  var
    Ch: AnsiChar;
  begin
    repeat
      ANode.NodeNew('').ReadFromStream(S);
      // Read AnsiCharacter, exit if none available
      repeat
        if S.Read(Ch, 1) = 0 then
          exit;
      // Read until end markup declaration or end
      until not (Ch in cControlChars);
      if Ch = ']' then
        break;
      S.Seek(-1, soCurrent);
    until False;
  end;
// main
var
  Prework: UTF8String;
  Ch: AnsiChar;
  Words: TsdUTF8StringList;
begin
  // Get the name and external ID
  Prework := '';
  repeat
    // Read AnsiCharacter, exit if none available
    if S.Read(Ch, 1) = 0 then
      exit;
    // Read until markup declaration or end
    if Ch in ['[', '>'] then
      break;
    Prework := Prework + UTF8String(Ch);
  until False;
  Words := TsdUTF8StringList.Create;
  try
    sdUTF8ParseAttributes(Prework, 1, length(Prework) + 1, Words);
    // First word is name
    if Words.Count > 0 then
    begin
      ANode.Name := Words[0];
      Words.Delete(0);
      // Put the rest in the valuedirect
      ANode.ValueDirect := sdUTF8Trim(sdUTF8StringReplace(Words.Text, #13#10, ' '));
    end;
  finally
    Words.Free;
  end;

  if Ch = '[' then
  begin

    // Parse any !ENTITY nodes and such
    ParseMarkupDeclarations;

    // read final tag
    repeat
      if S.Read(Ch, 1) = 0 then
        exit;
      if Ch = '>' then
        break;
    until False;

  end;
end;

procedure TNativeXml.ReadFromStream(S: TStream);
var
  i: integer;
  Node: TXmlNode;
  Enc: UTF8String;
  NormalCount, DeclarationCount,
  DoctypeCount, CDataCount: integer;
  NormalPos, DoctypePos: integer;
begin
  FAbortParsing := False;
  with FRootNodes do
  begin
    // Clear the old root nodes - we do not reset the defaults
    Clear;
    DoProgress(0);
    repeat
      Node := NodeNew('');
      Node.ReadFromStream(S);
      if AbortParsing then
        exit;

      // XML declaration
      if Node.ElementType = xeDeclaration then
      begin
        if Node.HasAttribute('encoding') then
          Enc := Node.AttributeByName['encoding']
        else
          FCodecStream.Encoding := seUTF8;
        // Check encoding
        if assigned(FCodecStream) and (AnsiUpperCase(string(Enc)) = 'UTF-8') then
          FCodecStream.Encoding := seUTF8;
      end;
      // Skip clear nodes
      if Node.IsClear then
        NodeDelete(NodeCount - 1);
    until S.Position >= S.Size;
    DoProgress(S.Size);

    // Do some checks
    NormalCount      := 0;
    DeclarationCount := 0;
    DoctypeCount     := 0;
    CDataCount       := 0;
    NormalPos        := -1;
    DoctypePos       := -1;
    for i := 0 to NodeCount - 1 do
    begin
      // Count normal elements - there may be only one
      case Nodes[i].ElementType of
      xeNormal:
        begin
          inc(NormalCount);
          NormalPos := i;
        end;
      xeDeclaration: inc(DeclarationCount);
      xeDoctype:
        begin
          inc(DoctypeCount);
          DoctypePos := i;
        end;
      xeCData: inc(CDataCount);
      end;//case
    end;

    // We *must* have a root node
    if NormalCount = 0 then
      raise EFilerError.Create(sxeNoRootElement);

    // Do some validation if we allow parser warnings
    if FParserWarnings then
    begin

      // Check for more than one root node
      if NormalCount > 1 then
        raise EFilerError.Create(sxeMoreThanOneRootElement);

      // Check for more than one xml declaration
      if DeclarationCount > 1 then
        raise EFilerError.Create(sxeMoreThanOneDeclaration);

      // Declaration must be first element if present
      if DeclarationCount = 1 then
        if Nodes[0].ElementType <> xeDeclaration then
          raise EFilerError.Create(sxeDeclarationMustBeFirstElem);

      // Check for more than one DTD
      if DoctypeCount > 1 then
        raise EFilerError.Create(sxeMoreThanOneDoctype);

      // Check if DTD is after root, this is not allowed
      if (DoctypeCount = 1) and (DoctypePos > NormalPos) then
        raise EFilerError.Create(sxeDoctypeAfterRootElement);

      // No CDATA in root allowed
      if CDataCount > 0 then
        raise EFilerError.Create(sxeCDataInRoot);
    end;
  end;//with
end;

procedure TNativeXml.ReadFromString(const AValue: UTF8String);
var
  S: TStream;
begin
  S := TsdUTF8StringStream.Create(AValue);
  try
    ReadFromStream(S);
  finally
    S.Free;
  end;
end;

procedure TNativeXml.ResolveEntityReferences;
begin
  if assigned(Root) then
    Root.ResolveEntityReferences;
end;

procedure TNativeXml.SaveToFile(const AFileName: string);
var
  S: TStream;
begin
  S := TFileStream.Create(AFileName, fmCreate);
  try
    SaveToStream(S);
  finally
    S.Free;
  end;
end;

procedure TNativeXml.SaveToStream(Stream: TStream);
var
  B: TsdBufferedWriteStream;
begin
  // Create buffer filter. Since we write a buffer at a time to the destination
  // stream, this speeds up the writing process for disk-based files.
  B := TsdBufferedWriteStream.Create(Stream, False);
  try
    // Create conversion stream
    FCodecStream := TsdUtf8Stream.Create(B);
    try
      // Set External encoding
      FCodecStream.Encoding := FExternalEncoding;
      WriteToStream(FCodecStream);
    finally
      FreeAndNil(FCodecStream);
    end;
  finally
    B.Free;
  end;
end;

procedure TNativeXml.SetCommentString(const Value: UTF8String);
// Find first comment node and set it's value, otherwise add new comment node
// right below the xml declaration
var
  Node: TXmlNode;
begin
  Node := FRootNodes.NodeByElementType(xeComment);
  if not assigned(Node) and (length(Value) > 0) then
  begin
    Node := TXmlNode.CreateType(Self, xeComment);
    FRootNodes.NodeInsert(1, Node);
  end;
  if assigned(Node) then
    Node.ValueAsString := Value;
end;

procedure TNativeXml.SetDefaults;
begin
  // Defaults
  FExternalEncoding       := cDefaultExternalEncoding;
  FXmlFormat              := cDefaultXmlFormat;
  FWriteOnDefault         := cDefaultWriteOnDefault;
  FBinaryEncoding         := cDefaultBinaryEncoding;
  FIndentString           := cDefaultIndentString;
  FDropCommentsOnParse    := cDefaultDropCommentsOnParse;
  FUseFullNodes           := cDefaultUseFullNodes;
  FUseLocalBias           := cDefaultUseLocalBias;
  FFloatAllowScientific   := cDefaultFloatAllowScientific;
  FFloatSignificantDigits := cDefaultFloatSignificantDigits;
  FOnNodeNew              := nil;
  FOnNodeLoaded           := nil;
end;

procedure TNativeXml.SetEncodingString(const Value: UTF8String);
var
  Node: TXmlNode;
begin
  if Value = GetEncodingString then
    exit;
  Node := FRootNodes[0];
  if not assigned(Node) or (Node.ElementType <> xeDeclaration) then
  begin
    Node := TXmlNode.CreateType(Self, xeDeclaration);
    FRootNodes.NodeInsert(0, Node);
  end;
  if assigned(Node) then
    Node.AttributeByName['encoding'] := Value;
end;

procedure TNativeXml.SetVersionString(const Value: UTF8String);
var
  Node: TXmlNode;
begin
  if Value = GetVersionString then
    exit;
  Node := FRootNodes[0];
  if not assigned(Node) or (Node.ElementType <> xeDeclaration) then
  begin
    if length(Value) > 0 then
    begin
      Node := TXmlNode.CreateType(Self, xeDeclaration);
      FRootNodes.NodeInsert(0, Node);
    end;
  end;
  if assigned(Node) then
    Node.AttributeByName['version'] := Value;
end;

procedure TNativeXml.WriteToStream(S: TStream);
var
  i: integer;
begin
  if not assigned(Root) and FParserWarnings then
    raise EFilerError.Create(sxeRootElementNotDefined);

  DoProgress(0);

  // write the root nodes
  for i := 0 to FRootNodes.NodeCount - 1 do
  begin
    FRootNodes[i].WriteToStream(S);
    sdUTF8WriteStringToStream(S, LineFeed);
  end;

  DoProgress(S.Size);
end;

function TNativeXml.WriteToString: UTF8String;
var
  S: TsdUTF8StringStream;
begin
  S := TsdUTF8StringStream.Create('');
  try
    WriteToStream(S);
    Result := S.DataString;
  finally
    S.Free;
  end;
end;

{ TsdCodecStream }

constructor TsdCodecStream.Create(AStream: TStream);
begin
  inherited Create;
  FStream := AStream;
end;

function TsdCodecStream.InternalRead(var Buffer{$IFDEF CLR}: array of Byte{$ENDIF}; Offset, Count: Longint): Longint;
// Read from FStream and pass back data
var
  i, j: integer;
  BOM: array[0..3] of byte;
  BytesRead: integer;
  Found: boolean;
begin
  Result := 0;
  if FMode = umUnknown then
  begin
    FMode := umRead;
    // Check FStream
    if not assigned(FStream) then
      raise EStreamError.Create(sxeCodecStreamNotAssigned);

    // Determine encoding
    FEncoding := seAnsi;
    BytesRead := FStream.Read(BOM, 4);
    for i := 0 to cBomInfoCount - 1 do
    begin
      Found := True;
      for j := 0 to Min(BytesRead, cBomInfo[i].Len) - 1 do
      begin
        if BOM[j] <> cBomInfo[i].BOM[j] then
        begin
          Found := False;
          break;
        end;
      end;
      if Found then
        break;
    end;
    if Found then
    begin
      FEncoding := cBomInfo[i].Encoding;
      FWriteBom := cBomInfo[i].HasBOM;
    end else
    begin
      // Unknown.. default to this
      FEncoding := seAnsi;
      FWriteBom := False;
    end;

    // Some encodings are not supported (yet)
    if FEncoding in [seUCS4BE, seUCS4_2143, seUCS4_3412, seEBCDIC] then
      raise EStreamError.Create(sxeUnsupportedEncoding);

    // Correct stream to start position
    if FWriteBom then
      FStream.Seek(cBomInfo[i].Len - BytesRead, soCurrent)
    else
      FStream.Seek(-BytesRead, soCurrent);

    // Check if we must swap byte order
    if FEncoding in [se16BitBE, seUTF16BE] then
      FSwapByteOrder := True;

  end;

  // Check mode
  if FMode <> umRead then
    raise EStreamError.Create(sxeCannotReadCodecForWriting);

  // Check count
  if Count <> 1 then
    raise EStreamError.Create(sxeCannotReadMultipeChar);

  // Now finally read
  TBytes(Buffer)[Offset] := ReadByte;
  if TBytes(Buffer)[Offset] <> 0 then Result := 1;
end;

{$IFDEF CLR}

function TsdCodecStream.Read(var Buffer: array of Byte; Offset, Count: Longint): Longint;
begin
  Result := InternalRead(Buffer, Offset, Count);
end;

{$ELSE}

function TsdCodecStream.Read(var Buffer; Count: Longint): Longint;
begin
  Result := InternalRead(Buffer, 0, Count);
end;

{$ENDIF}

function TsdCodecStream.ReadByte: byte;
begin
  // default does nothing
  Result := 0;
end;

function TsdCodecStream.InternalSeek(Offset: Longint; Origin: TSeekOrigin): Longint;
begin
  Result := 0;
  if FMode = umUnknown then
    raise EStreamError.Create(sxeCannotSeekBeforeReadWrite);

  if Origin = soCurrent then
  begin
    if Offset = 0 then
    begin
      // Position
      Result := FStream.Position;
      exit;
    end;
    if (FMode = umRead) and ((Offset = -1) or (Offset = -2)) then
    begin
      FBuffer := '';
      case Offset of
      -1: FStream.Seek(FPosMin1, soBeginning);
      -2: FStream.Seek(FPosMin2, soBeginning);
      end;//case
      exit;
    end;
  end;
  if (Origin = soEnd) and (Offset = 0) then
  begin
    // Size
    Result := FStream.Size;
    exit;
  end;
  // Ignore set position from beginning (used in Size command)
  if Origin = soBeginning then
    exit;
  // Arriving here means we cannot do it
  raise EStreamError.Create(sxeCannotPerformSeek);
end;

{$IFDEF CLR}

function TsdCodecStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64;
begin
  Result := InternalSeek(Offset, Origin);
end;

{$ELSE}

function TsdCodecStream.Seek(Offset: Longint; Origin: Word): Longint;
begin
  Result := InternalSeek(Offset, TSeekOrigin(Origin));
end;

{$ENDIF}

procedure TsdCodecStream.StorePrevPositions;
begin
  FPosMin2 := FPosMin1;
  FPosMin1 := FStream.Position;
end;

function TsdCodecStream.InternalWrite(const Buffer{$IFDEF CLR}: array of Byte{$ENDIF}; Offset, Count: Longint): Longint;
var
  i: integer;
begin
  if FMode = umUnknown then
  begin
    FMode := umWrite;

    // Some encodings are not supported (yet)
    if FEncoding in [seUCS4BE, seUCS4_2143, seUCS4_3412, seEBCDIC] then
      raise EStreamError.Create(sxeUnsupportedEncoding);

    // Find correct encoding info
    for i := 0 to cBomInfoCount - 1 do
      if cBomInfo[i].Encoding = FEncoding then
      begin
        // we do not write BOM if UTF8 since UTF8 is default
        FWriteBom := cBomInfo[i].HasBOM and (FEncoding <>  seUTF8);
        break;
      end;

    // Write BOM
    if FWriteBom then
      FStream.WriteBuffer(cBomInfo[i].BOM, cBomInfo[i].Len);

    // Check if we must swap byte order
    if FEncoding in [se16BitBE, seUTF16BE] then
      FSwapByteOrder := True;
  end;

  if FMode <> umWrite then
    raise EStreamError.Create(sxeCannotWriteCodecForReading);
  WriteBuf(Buffer, Offset, Count);
  Result := Count;
end;

{$IFDEF CLR}

function TsdCodecStream.Write(const Buffer: array of Byte; Offset, Count: Longint): Longint;
begin
  Result := InternalWrite(Buffer, Offset, Count);
end;

{$ELSE}

function TsdCodecStream.Write(const Buffer; Count: Longint): Longint;
begin
  Result := InternalWrite(Byte(Buffer), 0, Count);
end;

{$ENDIF}

procedure TsdCodecStream.WriteBuf(const Buffer{$IFDEF CLR}: TBytes{$ENDIF}; Offset, Count: longint);
var
  i: integer;
begin
  // Default just writes out bytes one by one. We override this in descendants
  // to provide faster writes for some modes
  for i := 0 to Count - 1 do
  {$IFDEF CLR}
    WriteByte(Buffer[Offset + i]);
  {$ELSE}
    WriteByte(TBytes(Buffer)[Offset + i]);
  {$ENDIF}
end;

procedure TsdCodecStream.WriteByte(const B: byte);
begin
// default does nothing
end;

{$IFDEF CLR}

procedure TsdCodecStream.SetSize(NewSize: Int64);
begin
// default does nothing
end;

{$ENDIF}

{ TsdUtf8Stream }

function TsdUtf8Stream.ReadByte: byte;
var
  B, B1, B2, B3: byte;
  W: word;
  SA: AnsiString;
begin
  Result := 0;

  // New AnsiCharacter?
  if (Length(FBuffer) = 0) or (FBufferPos > length(FBuffer)) then
  begin
    StorePrevPositions;
    FBufferPos := 1;
    // Read another AnsiChar and put in buffer
    case FEncoding of
    seAnsi:
      begin
        // read one byte
        B := 0;
        FStream.Read(B, 1);
        SA := AnsiChar(B);
        // Convert to UTF8
        FBuffer := sdAnsiToUtf8(SA);
      end;
    seUTF8:
      begin
        // Read one, two or three bytes in the buffer
        B1 := 0;
        FStream.Read(B1, 1);
        FBuffer := AnsiChar(B1);
        if (B1 and $80) > 0 then
        begin
          if (B1 and $20) <> 0 then
          begin
            B2 := 0;
            FStream.Read(B2, 1);
            FBuffer := FBuffer + UTF8String(AnsiChar(B2));
          end;
          B3 := 0;
          FStream.Read(B3, 1);
          FBuffer := FBuffer + UTF8String(AnsiChar(B3));
        end;
      end;
    se16BitBE, se16BitLE, seUTF16BE, seUTF16LE:
      begin
        // Read two bytes
        W := 0;
        FStream.Read(W, 2);
        // Swap byte order
        if FSwapByteOrder then
          W := swap(W);
        // Convert to UTF8 in buffer
        FBuffer := sdUnicodeToUtf8(UnicodeChar(W));
      end;
    else
      raise EStreamError.Create(sxeUnsupportedEncoding);
    end;//case
  end;

  // Now we have the buffer, so read
  if (FBufferPos > 0) and (FBufferPos <= length(FBuffer)) then
    Result := byte(FBuffer[FBufferPos]);
  inc(FBufferPos);
end;

procedure TsdUtf8Stream.WriteBuf(const Buffer{$IFDEF CLR}: TBytes{$ENDIF}; Offset, Count: longint);
begin
  case FEncoding of
  seUtf8:
    begin
      // one on one
      if StreamWrite(FStream, Buffer, Offset, Count) <> Count then
        raise EStreamError.Create(sxeCannotWriteToOutputStream);
    end
  else
    inherited;
  end;//case
end;

procedure TsdUtf8Stream.WriteByte(const B: byte);
var
  SA: AnsiString;
  SW: UnicodeString;
  MustWrite: boolean;
begin
  case FEncoding of
  seAnsi, se16BitBE, se16BitLE, seUTF16BE, seUTF16LE:
    begin
      MustWrite := True;
      case Length(FBuffer) of
      0:
        begin
          FBuffer := AnsiChar(B);
          if (B and $80) <> 0 then
            MustWrite := False;
        end;
      1:
        begin
          FBuffer := FBuffer + UTF8String(AnsiChar(B));
          if (byte(FBuffer[1]) and $20) <> 0 then
            MustWrite := False;
        end;
      2: FBuffer := FBuffer + UTF8String(AnsiChar(B));
      end;
      if MustWrite then
      begin
        if FEncoding = seAnsi then
        begin
          // Convert to ansi
          SA := sdUtf8ToAnsi(FBuffer);
          // write out
          if length(SA) = 1 then
            if FStream.Write(SA[1], 1) <> 1 then
              raise EStreamError.Create(sxeCannotWriteToOutputStream);
        end else
        begin
          // Convert to unicode
          SW := sdUtf8ToUnicode(FBuffer);
          // write out
          if length(SW) = 1 then
            if FStream.Write(SW[1], 2) <> 2 then
              raise EStreamError.Create(sxeCannotWriteToOutputStream);
        end;
        FBuffer := '';
      end;
    end;
  seUTF8:
    begin
      // Just a flat write of one byte
      if FStream.Write(B, 1) <> 1 then
        raise EStreamError.Create(sxeCannotWriteToOutputStream);
    end;
  else
    raise EStreamError.Create(sxeUnsupportedEncoding);
  end;//case
end;

{$IFDEF CLR}
{ TsdBufferedStream }

constructor TsdBufferedStream.Create(AStream: TStream; Owned: Boolean = False);
begin
  inherited Create;
  FStream := AStream;
  FOwned := Owned;
end;

destructor TsdBufferedStream.Destroy;
begin
  if FOwned then FreeAndNil(FStream);
  inherited Destroy;
end;

function TsdBufferedStream.Read(var Buffer: array of Byte; Offset, Count: Longint): Longint;
begin
  Result := FStream.Read(Buffer, Offset, Count);
end;

function TsdBufferedStream.Write(const Buffer: array of Byte; Offset, Count: Longint): Longint;
begin
  Result := FStream.Write(Buffer, Offset, Count);
end;

function TsdBufferedStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64;
begin
  Result := FStream.Seek(Offset, Origin);
end;

procedure TsdBufferedStream.SetSize(NewSize: Int64);
begin
  FStream.Size := NewSize;
end;

{$ELSE}

{ TsdBufferedReadStream }

const
  cMaxBufferSize = $10000; // 65536 bytes in the buffer

procedure TsdBufferedReadStream.CheckPosition;
var
  NewPage: integer;
  FStartPos: longint;
begin
  // Page and buffer position
  NewPage := FPosition div cMaxBufferSize;
  FBufPos := FPosition mod cMaxBufferSize;

  // Read new page if required
  if (NewPage <> FPage) then
  begin
    // New page and buffer
    FPage := NewPage;

    // Start position in stream
    FStartPos := FPage * cMaxBufferSize;
    FBufSize  := Min(cMaxBufferSize, FStream.Size - FStartPos);

    FStream.Seek(FStartPos, soBeginning);
    if FBufSize > 0 then
      FStream.Read(FBuffer^, FBufSize);
  end;
  FMustCheck := False;
end;

constructor TsdBufferedReadStream.Create(AStream: TStream; Owned: boolean);
begin
  inherited Create;
  FStream := AStream;
  FOwned := Owned;
  FMustCheck := True;
  FPage := -1; // Set to invalid number to force an update on first read
  ReallocMem(FBuffer, cMaxBufferSize);
end;

destructor TsdBufferedReadStream.Destroy;
begin
  if FOwned then FreeAndNil(FStream);
  ReallocMem(FBuffer, 0);
  inherited;
end;

function TsdBufferedReadStream.Read(var Buffer; Count: longint): Longint;
var
  Packet: PByte;
  PacketCount: integer;
begin
  // Set the right page
  if FMustCheck then
    CheckPosition;

  // Special case - read one byte, most often
  if (Count = 1) and (FBufPos < FBufSize - 1) then
  begin
    byte(Buffer) := FBuffer^[FBufPos];
    inc(FBufPos);
    inc(FPosition);
    Result := 1;
    exit;
  end;

  // general case
  Packet := @Buffer;
  Result := 0;
  while Count > 0 do
  begin
    PacketCount := min(FBufSize - FBufPos, Count);
    if PacketCount <= 0 then
      exit;
    Move(FBuffer^[FBufPos], Packet^, PacketCount);
    dec(Count, PacketCount);
    inc(Packet, PacketCount);
    inc(Result, PacketCount);
    inc(FPosition, PacketCount);
    inc(FBufPos, PacketCount);
    if FBufPos >= FBufSize then
      CheckPosition;
  end;
end;

function TsdBufferedReadStream.Seek(Offset: longint; Origin: Word): Longint;
begin
  case Origin of
  soFromBeginning:
    FPosition := Offset;
  soFromCurrent:
    begin
      // no need to check in this case - it is the GetPosition command
      if Offset = 0 then
      begin
        Result := FPosition;
        exit;
      end;
      FPosition := FPosition + Offset;
    end;
  soFromEnd:
    FPosition := FStream.Size + Offset;
  end;//case
  Result := FPosition;
  FMustCheck := True;
end;

function TsdBufferedReadStream.Write(const Buffer; Count: longint): Longint;
begin
  raise EStreamError.Create(sxeCannotWriteCodecForReading);
end;

{ TsdBufferedWriteStream }

constructor TsdBufferedWriteStream.Create(AStream: TStream; Owned: boolean);
begin
  inherited Create;
  FStream := AStream;
  FOwned := Owned;
  ReallocMem(FBuffer, cMaxBufferSize);
end;

destructor TsdBufferedWriteStream.Destroy;
begin
  Flush;
  if FOwned then
    FreeAndNil(FStream);
  ReallocMem(FBuffer, 0);
  inherited;
end;

procedure TsdBufferedWriteStream.Flush;
begin
  // Write the buffer to the stream
  if FBufPos > 0 then
  begin
    FStream.Write(FBuffer^, FBufPos);
    FBufPos := 0;
  end;
end;

function TsdBufferedWriteStream.Read(var Buffer; Count: longint): Longint;
begin
  raise EStreamError.Create(sxeCannotReadCodecForWriting);
end;

function TsdBufferedWriteStream.Seek(Offset: longint; Origin: Word): Longint;
begin
  case Origin of
  soFromBeginning:
    if Offset = FPosition then
    begin
      Result := FPosition;
      exit;
    end;
  soFromCurrent:
    begin
      // GetPosition command
      if Offset = 0 then
      begin
        Result := FPosition;
        exit;
      end;
    end;
  soFromEnd:
    if Offset = 0 then
    begin
      Result := FPosition;
      exit;
    end;
  end;//case
  raise EStreamError.Create(sxeCannotPerformSeek);
end;

function TsdBufferedWriteStream.Write(const Buffer; Count: longint): Longint;
var
  Packet: PByte;
  PacketCount: integer;
begin
  // Special case - read less bytes than would fill buffersize
  if (FBufPos + Count < cMaxBufferSize) then
  begin
    Move(Buffer, FBuffer^[FBufPos], Count);
    inc(FBufPos, Count);
    inc(FPosition, Count);
    Result := Count;
    exit;
  end;

  // general case that wraps buffer
  Packet := @Buffer;
  Result := 0;
  while Count > 0 do
  begin
    PacketCount := min(cMaxBufferSize - FBufPos, Count);
    if PacketCount <= 0 then
      exit;
    Move(Packet^, FBuffer^[FBufPos], PacketCount);
    dec(Count,     PacketCount);
    inc(Result,    PacketCount);
    inc(FPosition, PacketCount);
    inc(Packet,    PacketCount);
    inc(FBufPos,   PacketCount);
    if FBufPos = cMaxBufferSize then
      Flush;
  end;
end;
{$ENDIF}

{ TsdSurplusReader }

constructor TsdSurplusReader.Create(AStream: TStream);
begin
  inherited Create;
  FStream := AStream;
end;

function TsdSurplusReader.ReadChar(var Ch: AnsiChar): integer;
begin
  if length(FSurplus) > 0 then
  begin
    Ch := FSurplus[1];
    FSurplus := copy(FSurplus, 2, length(FSurplus) - 1);
    Result := 1;
  end else
    Result := FStream.Read(Ch, 1);
end;

function TsdSurplusReader.ReadCharSkipBlanks(var Ch: AnsiChar): boolean;
begin
  Result := False;
  repeat
    // Read AnsiCharacter, exit if none available
    if ReadChar(Ch) = 0 then
      exit;
    // Skip if in controlchars
    if not (Ch in cControlchars) then
      break;
  until False;
  Result := True;
end;

{ TsdStringBuilder }

procedure TsdStringBuilder.AddChar(Ch: AnsiChar);
begin
  inc(FCurrentIdx);
  Reallocate(FCurrentIdx);
  FData[FCurrentIdx] := Ch;
end;

procedure TsdStringBuilder.AddString(var S: UTF8String);
var
  {$IFDEF CLR}
  i: integer;
  {$ENDIF}
  Count: integer;
begin
  {$IFDEF CLR}
  Count := S.Length;
  {$ELSE}
  Count := System.length(S);
  {$ENDIF}
  if Count = 0 then
    exit;
  Reallocate(FCurrentIdx + Count);
  {$IFDEF CLR}
  for i := 1 to S.Length do
    FData[FCurrentIdx + i] := S[i];
  {$ELSE}
  Move(S[1], FData[FCurrentIdx + 1], Count);
  {$ENDIF}
  inc(FCurrentIdx, Count);
end;

procedure TsdStringBuilder.Clear;
begin
  FCurrentIdx := 0;
end;

function TsdStringBuilder.StringCopy(AFirst, ALength: integer): UTF8String;
begin
  if ALength > FCurrentIdx - AFirst + 1 then
    ALength := FCurrentIdx - AFirst + 1;
  Result := Copy(FData, AFirst, ALength);
end;

constructor TsdStringBuilder.Create;
begin
  inherited Create;
  SetLength(FData, 64);
end;

function TsdStringBuilder.GetData(Index: integer): AnsiChar;
begin
  Result := FData[Index];
end;

procedure TsdStringBuilder.Reallocate(RequiredLength: integer);
begin
  {$IFDEF CLR}
  while FData.Length < RequiredLength do
    SetLength(FData, FData.Length * 2);
  {$ELSE}
  while System.Length(FData) < RequiredLength do
    SetLength(FData, System.Length(FData) * 2);
  {$ENDIF}
end;

function TsdStringBuilder.Value: UTF8String;
begin
  Result := Copy(FData, 1, FCurrentIdx);
end;

end.

Added src/NativeXml/NativeXmlXPath.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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
unit NativeXmlXPath;

interface
uses
  SysUtils, Classes,
  NativeXml;

type
  TXmlNodeHelper = class helper for TXmlNode
  const
    XMLFS: TFormatSettings = (DateSeparator: '-'; TimeSeparator: ':'; ListSeparator: ' ';
                              ShortDateFormat: 'YYYY-MM-dd'; LongDateFormat: 'YYYY-MM-dd';
                              ShortTimeFormat: 'HH:nn:ss'; LongTimeFormat: 'HH:nn:ss';
                              ThousandSeparator: #0; DecimalSeparator: '.');
  type
    TXmlNodeFilter = reference to function(Node: TXmlNode): Boolean;
    TWalkDirection = (wdTopDownFirstToLast, wdTopDownLastToFirst, wdBottomUpFirstToLast, wdBottomUpLastToFirst);
  private
    function ProcessXPath(const StartNode: TXmlNode; XPath: string;
                          const ResultNodes: TList; const StopWhenFound: Boolean): Integer;
    function GetXML: string;
    function GetPrefixNamespace(const Prefix: string): string;
    function GetNamespace: string;
    function GetLocalName: string;
    function GetPrefix: string;
  public
    function WalkSubtree(const Direction: TWalkDirection; const Filter: TXmlNodeFilter): Boolean; overload; inline;
    function WalkSubtree(const Direction: TWalkDirection; const Depth: Cardinal; const Filter: TXmlNodeFilter): Boolean; overload;

    function ForceNamespace(const TargetNS: string; const NamespacePrefixes: TStrings = nil): boolean;

    function HasChildNode(const Name: string): Boolean;

    function CountNodes(const XPath: string): Integer;
    function SelectNode(XPath: string): TXmlNode;
    function SelectNodes(const XPath: string): TXmlNodeList; overload;
    function SelectNodes(XPath: string; const Nodes: TList): Integer; overload;

    function AsBoolean(const Default: Boolean = False): Boolean;
    function AsDateTime(const Default: TDateTime = 0): TDateTime;
    function AsFloat(const Default: Extended = 0.0): Extended;
//    function AsDoubleList(const Default: Double = 0.0): TDoubleIntegerList;
    function AsInteger(const Default: Integer = 0): Integer;
    function AsInt64(const Default: Int64 = 0): Int64;
    function AsString(const Default: string = ''): string;
    function AsUTF8String(const Default: UTF8String = ''): UTF8String;
    function AsEnum<T>(): T; overload;
    function AsEnum<T>(const DefaultValue: T): T; overload;
    function AsEnum<T>(const Names: array of string): T; overload;
    function AsEnum<T>(const Names: array of string; const DefaultValue: T): T; overload;

    procedure SetValueAsEnum<T>(const Value: T); overload;
    procedure SetValueAsEnum<T>(const Value: T; const Names: array of string); overload;

    function AttrAsBoolean(const Name: string; const Default: Boolean = False): Boolean;
    function AttrAsDateTime(const Name: string; const Default: TDateTime = 0): TDateTime;
    function AttrAsFloat(const Name: string; const Default: Extended = 0.0): Extended;
//    function AttrAsDoubleList(const Name: string; const Default: Double = 0.0): TDoubleIntegerList;
    function AttrAsInteger(const Name: string; const Default: Integer = 0): Integer;
    function AttrAsInt64(const Name: string; const Default: Int64 = 0): Int64;
    function AttrAsString(const Name: string; const Default: string = ''): string;
    function AttrAsUTF8String(const Name: string; const Default: UTF8String = ''): UTF8String;
    function AttrAsEnum<T>(const Name: string): T; overload;
    function AttrAsEnum<T>(const Name: string; const DefaultValue: T): T; overload;
    function AttrAsEnum<T>(const Name: string; const Names: array of string): T; overload;
    function AttrAsEnum<T>(const Name: string; const Names: array of string; const DefaultValue: T): T; overload;

    property LocalName: string  read GetLocalName;
    property Prefix: string     read GetPrefix;
    property Namespace: string  read GetNamespace;
    property XML: string        read GetXML;
  end;


  TNativeXmlHelper = class helper for TNativeXml
  public
    function CountNodes(const XPath: string): Integer;
    function SelectNode(const XPath: string): TXmlNode;
    function SelectNodes(const XPath: string): TXmlNodeList; overload;
    function SelectNodes(const XPath: string; const Nodes: TList): Integer; overload;
  end;


  TXmlNodeListHelper = class helper for TXmlNodeList
  private
    type
      TXmlNodeListEnumerator = class
      private
        FList: TXmlNodeList;
        FIndex: Integer;
        function GetCurrent: TXmlNode; inline;
      public
        constructor Create(const List: TXmlNodeList);
        function MoveNext: Boolean;
        property Current: TXmlNode read GetCurrent;
      end;
  public
    function GetEnumerator: TXmlNodeListEnumerator;
  end;


implementation

uses
  Windows, StrUtils, TypInfo, Character,
  SimpleGenericEnum;

{ ================================================================================================ }
{ TXmlNodeHelper }

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.AsBoolean(const Default: Boolean): Boolean;
begin
{$IFDEF DEBUG}
  if not Assigned(Self) then
    OutputDebugString('NIL NODE REQUESTED');
{$ENDIF}
  if not Assigned(Self) then Exit(Default);
  Result := Self.ValueAsBoolDef(Default);
end {TXmlNodeHelper.AsBoolean};

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.AsDateTime(const Default: TDateTime): TDateTime;
begin
{$IFDEF DEBUG}
  if not Assigned(Self) then
    OutputDebugString('NIL NODE REQUESTED');
{$ENDIF}
  if not Assigned(Self) then Exit(Default);
  Result := Self.ValueAsDateTimeDef(Default);
end {TXmlNodeHelper.AsDateTime};

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.AsFloat(const Default: Extended): Extended;
begin
{$IFDEF DEBUG}
  if not Assigned(Self) then
    OutputDebugString('NIL NODE REQUESTED');
{$ENDIF}
  if not Assigned(Self) then Exit(Default);
  Result := Self.ValueAsFloatDef(Default);
end {TXmlNodeHelper.AsFloat};

//{ ------------------------------------------------------------------------------------------------ }
//function TXmlNodeHelper.AsDoubleList(const Default: Double): TDoubleIntegerList;
//var
//  Values: TStringList;
//  i: Integer;
//  XMLFS: TFormatSettings;
//  Value: Double;
//begin
//{$IFDEF DEBUG}
//  if not Assigned(Self) then
//    OutputDebugString('NIL NODE REQUESTED');
//{$ENDIF}
//  Result := TDoubleIntegerList.Create;
//  if not Assigned(Self) then Exit;
//  try
//    Values := TStringList.Create;
//    try
//      Values.Delimiter := ' ';
//      Values.StrictDelimiter := True;
//      Values.DelimitedText := Self.AsString;
//
//      XMLFS.ThousandSeparator := ',';
//      XMLFS.DecimalSeparator := '.';
//      for i := 0 to Values.Count - 1 do begin
//        if TryStrToFloat(Values[i], Value, XMLFS) then begin
//          Result.Add(Value);
//        end else begin
//          Result.Add(Default);
//        end;
//      end;
//    finally
//      Values.Free;
//    end;
//  except
//    FreeAndNil(Result);
//    raise;
//  end;
//end {TXmlNodeHelper.AsDoubleList};

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.AsEnum<T>: T;
begin
  Result := Self.AsEnum<T>(Default(T));
end {TXmlNodeHelper.AsEnum<T>};

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.AsEnum<T>(const DefaultValue: T): T;
begin
{$IFDEF DEBUG}
  if not Assigned(Self) then
    OutputDebugString('NIL NODE REQUESTED');
{$ENDIF}
  if not Assigned(Self) or not TEnum<T>.StrToEnum(ValueAsUnicodeString, Result) then
    Result := DefaultValue;
end {TXmlNodeHelper.AsEnum<T>};

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.AsEnum<T>(const Names: array of string): T;
begin
  Result := Self.AsEnum<T>(Names, Default(T));
end {TXmlNodeHelper.AsEnum<T>};

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.AsEnum<T>(const Names: array of string; const DefaultValue: T): T;
var
  i: Integer;
  Value: string;
begin
{$IFDEF DEBUG}
  if not Assigned(Self) then
    OutputDebugString('NIL NODE REQUESTED');
{$ENDIF}
  if Assigned(Self) then begin
    Value := ValueAsUnicodeString;
    for i := Low(Names) to High(Names) do begin
      if SameText(Value, Names[i]) then
        Result := TEnum<T>.Cast(i);
        Exit;
    end;
  end;
  Result := DefaultValue;
end {TXmlNodeHelper.AsEnum<T>};

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.AsInt64(const Default: Int64): Int64;
begin
{$IFDEF DEBUG}
  if not Assigned(Self) then
    OutputDebugString('NIL NODE REQUESTED');
{$ENDIF}
  if not Assigned(Self) then Exit(Default);
  Result := Self.ValueAsInt64Def(Default);
end {TXmlNodeHelper.AsInt64};

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.AsInteger(const Default: Integer): Integer;
begin
{$IFDEF DEBUG}
  if not Assigned(Self) then
    OutputDebugString('NIL NODE REQUESTED');
{$ENDIF}
  if not Assigned(Self) then Exit(Default);
  Result := Self.ValueAsIntegerDef(Default);
end {TXmlNodeHelper.AsInteger};

{ ------------------------------------------------------------------------------------------------ }
function Unescape(const XML: string): string;
const
  cEntities: array[1..5] of string = ('amp', 'apos', 'gt', 'lt', 'quot');
  cEnttRepl: array[1..5] of string = ('&',   '''',   '>',  '<',  '"');
var
  i, ni, ei: Integer;
  Entity, Replacement: string;
begin
  Result := ''; // StringOfChar(#0, Length(XML));
  ni := 1;
  i := Pos('&', XML);
  while i > 0 do begin
    Result := Result + Copy(XML, ni, i - ni);
    ni := Pos(';', XML, i + 1);
    if ni = 0 then begin
      Result := Result + '&';
      ni := i + 1;
    end else begin
      if XML[i + 1] = '#' then begin
        if XML[i + 2].IsInArray(['x', 'X']) then begin
          // Hex
          Result := Result + Char(StrToInt('$' + Copy(XML, i + 3, ni - i - 3)));
        end else begin
          // Decimal
          Result := Result + Char(StrToInt(Copy(XML, i + 2, ni - i - 2)));
        end;
      end else begin
        // Entity
        Entity := Copy(XML, i + 1, ni - i - 1);
        Replacement := Entity;
        for ei := Low(cEntities) to High(cEntities) do begin
          case CompareStr(Entity, cEntities[ei]) of
            0: begin
              Replacement := cEnttRepl[ei];
              Break;
            end;
            1: begin // laat maar, we zijn er al voorbij
              Break;
            end;
          end;
        end {for};
        Result := Result + Replacement;
      end;
      ni := ni + 1;
    end;
    i := Pos('&', XML, ni);
  end;
  // Copy remaining characters
  Result := Result + Copy(XML, ni);
end{Unescape};

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.AsString(const Default: string): string;
begin
{$IFDEF DEBUG}
  if not Assigned(Self) then
    OutputDebugString('NIL NODE REQUESTED');
{$ENDIF}
  if not Assigned(Self) then Exit(Default);
  if Self.ElementType = xeNormal then
    Result := Unescape(Trim(string(Self.ValueDirect)))
  else
    Result := Unescape(string(Self.ValueDirect));
end {TXmlNodeHelper.AsString};

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.AsUTF8String(const Default: UTF8String): UTF8String;
begin
{$IFDEF DEBUG}
  if not Assigned(Self) then
    OutputDebugString('NIL NODE REQUESTED');
{$ENDIF}
  if not Assigned(Self) then Exit(Default);
  Result := Self.ValueAsString;
end {TXmlNodeHelper.AsString};


{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.AttrAsBoolean(const Name: string; const Default: Boolean): Boolean;
var
  Index: Integer;
begin
{$IFDEF DEBUG}
  if not Assigned(Self) then
    OutputDebugString('NIL NODE REQUESTED');
{$ENDIF}
  if not Assigned(Self) then Exit(Default);
  Index := Self.AttributeIndexByname(UTF8String(Name));
  if not ((Index > -1) and TryStrToBool(string(Self.AttributeValue[Index]), Result)) then
    Result := Default;
end;

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.AttrAsDateTime(const Name: string; const Default: TDateTime): TDateTime;
var
  Index: Integer;
begin
{$IFDEF DEBUG}
  if not Assigned(Self) then
    OutputDebugString('NIL NODE REQUESTED');
{$ENDIF}
  if not Assigned(Self) then Exit(Default);
  Index := Self.AttributeIndexByname(UTF8String(Name));
  if Index = -1 then
    Result := Default
  else
    Result := sdDateTimeFromStringDefault(Self.AttributeValue[Index], Default);
end;

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.AttrAsEnum<T>(const Name: string; const DefaultValue: T): T;
var
  Index: Integer;
begin
{$IFDEF DEBUG}
  if not Assigned(Self) then
    OutputDebugString('NIL NODE REQUESTED');
{$ENDIF}
  if not Assigned(Self) then Exit(DefaultValue);
  Index := Self.AttributeIndexByname(UTF8String(Name));
  if (Index = -1) or not TEnum<T>.StrToEnum(string(Self.AttributeValue[Index]), Result) then
    Result := DefaultValue;
end;

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.AttrAsEnum<T>(const Name: string): T;
begin
  Result := AttrAsEnum<T>(Name, Default(T));
end;

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.AttrAsEnum<T>(const Name: string; const Names: array of string;
  const DefaultValue: T): T;
var
  Index, i: Integer;
  Value: string;
begin
{$IFDEF DEBUG}
  if not Assigned(Self) then
    OutputDebugString('NIL NODE REQUESTED');
{$ENDIF}
  if Assigned(Self) then begin
    Index := Self.AttributeIndexByname(UTF8String(Name));
    if Index > -1 then begin
      Value := Self.AttributeValueAsUnicodeString[Index];
      for i := Low(Names) to High(Names) do begin
        if SameText(Value, Names[i]) then
          Result := TEnum<T>.Cast(i);
          Exit;
      end {for};
    end {if};
  end {if};
  Result := DefaultValue;
end;

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.AttrAsEnum<T>(const Name: string; const Names: array of string): T;
begin
  Result := AttrAsEnum<T>(Name, Names, Default(T));
end;


{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.AttrAsFloat(const Name: string; const Default: Extended): Extended;
var
  Index: Integer;
begin
{$IFDEF DEBUG}
  if not Assigned(Self) then
    OutputDebugString('NIL NODE REQUESTED');
{$ENDIF}
  if not Assigned(Self) then Exit(Default);
  Index := Self.AttributeIndexByname(UTF8String(Name));
  if not ((Index > -1) and TryStrToFloat(string(Self.AttributeValue[Index]), Result, XMLFS)) then
    Result := Default;
end;

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.AttrAsInt64(const Name: string; const Default: Int64): Int64;
var
  Index: Integer;
begin
{$IFDEF DEBUG}
  if not Assigned(Self) then
    OutputDebugString('NIL NODE REQUESTED');
{$ENDIF}
  if not Assigned(Self) then Exit(Default);
  Index := Self.AttributeIndexByname(UTF8String(Name));
  if not ((Index > -1) and TryStrToInt64(string(Self.AttributeValue[Index]), Result)) then
    Result := Default;
end;

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.AttrAsInteger(const Name: string; const Default: Integer): Integer;
var
  Index: Integer;
begin
{$IFDEF DEBUG}
  if not Assigned(Self) then
    OutputDebugString('NIL NODE REQUESTED');
{$ENDIF}
  if not Assigned(Self) then Exit(Default);
  Index := Self.AttributeIndexByname(UTF8String(Name));
  if not ((Index > -1) and TryStrToInt(string(Self.AttributeValue[Index]), Result)) then
    Result := Default;
end;

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.AttrAsString(const Name, Default: string): string;
var
  Index: Integer;
begin
{$IFDEF DEBUG}
  if not Assigned(Self) then
    OutputDebugString('NIL NODE REQUESTED');
{$ENDIF}
  if not Assigned(Self) then Exit(Default);
  Index := Self.AttributeIndexByname(UTF8String(Name));
  if Index = -1 then
    Result := Default
  else
    Result := Self.AttributeValueAsUnicodeString[Index];
end;

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.AttrAsUTF8String(const Name: string; const Default: UTF8String): UTF8String;
var
  Index: Integer;
begin
{$IFDEF DEBUG}
  if not Assigned(Self) then
    OutputDebugString('NIL NODE REQUESTED');
{$ENDIF}
  if not Assigned(Self) then Exit(Default);
  Index := Self.AttributeIndexByname(UTF8String(Name));
  if Index = -1 then
    Result := Default
  else
    Result := Self.AttributeValue[Index];
end;

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.ProcessXPath(const StartNode: TXmlNode; XPath: string;
                                     const ResultNodes: TList; const StopWhenFound: Boolean): Integer;
var
  Recursive: boolean;
  SlashPos: Integer;
  NodeName: string;
  i: Integer;
  Child: TXmlNode;
  NodesToSearch: TList;
label
  FindFirstSlash;
begin
  Result := 0;
  Recursive := False;

FindFirstSlash:
  SlashPos := Pos('/', XPath);
  case SlashPos of
    0: begin // no slash present
      NodeName := XPath;
      XPath := '';
    end;
    1: begin // starting with a slash; this was '//'
      Recursive := True;
      XPath := Copy(XPath, 2);
      goto FindFirstSlash;
    end;
    else begin
      NodeName := Copy(XPath, 1, SlashPos - 1);
      XPath := Copy(XPath, SlashPos + 1);
    end;
  end;

  if (NodeName = '') and (XPath = '') then begin
    if Assigned(ResultNodes) then
    ResultNodes.Add(StartNode);
    Result := 1;
    Exit;
  end else if NodeName = '.' then begin
    Assert(not Recursive, 'The expression "//." is not supported.');
    Result := Result + ProcessXPath(StartNode, XPath, ResultNodes, StopWhenFound);
    if StopWhenFound and (Result > 0) then
      Exit;
  end else if NodeName = '..' then begin
    Assert(not Recursive, 'The expression "//.." is not supported.');
    Result := Result + ProcessXPath(StartNode.Parent, XPath, ResultNodes, StopWhenFound);
    if StopWhenFound and (Result > 0) then
      Exit;
  end else if NodeName = '*' then begin
    Assert(not Recursive, 'The expression "//*" is not supported.');
    NodeName := '';
  end;

  if Recursive then begin
    NodesToSearch := TList.Create;
    try
      StartNode.FindNodes(UTF8String(NodeName), NodesToSearch);
      for i := 0 to NodesToSearch.Count - 1 do begin
        Child := NodesToSearch[i];
        Result := Result + ProcessXPath(Child, XPath, ResultNodes, StopWhenFound);
        if StopWhenFound and (Result > 0) then
          Exit;
      end;
    finally
      NodesToSearch.Free;
    end;
  end else begin
    for i := 0 to StartNode.NodeCount - 1 do begin
      Child := StartNode.Nodes[i];
      if (NodeName = '') or (string(Child.Name) = NodeName) then begin
        Result := Result + ProcessXPath(Child, XPath, ResultNodes, StopWhenFound);
        if StopWhenFound and (Result > 0) then
          Exit;
      end;
    end;
  end;

end {TXmlNodeHelper.ProcessXPath};

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.SelectNode(XPath: string): TXmlNode;
var
  Nodes: TList;
  Queries: TArray<string>;
  qi: Integer;
  SlashPos: integer;
  NodeName: string;
begin
{$IFDEF DEBUG}
  if not Assigned(Self) then
    OutputDebugString('NIL NODE REQUESTED');
{$ENDIF}
  if not Assigned(Self) then
    Exit(nil);

  Nodes := TList.Create;
  try
    Queries := XPath.Split(['|']);
    for qi := Low(Queries) to High(Queries) do begin
      XPath := Queries[qi];
      if Copy(XPath, 1, 1) = '/' then begin
        XPath := Copy(XPath, 2);
        SlashPos := Pos('/', XPath);
        if SlashPos = 0 then begin
          NodeName := XPath;
          XPath := '';
        end else begin
          NodeName := Copy(XPath, 1, SlashPos - 1);
          XPath := Copy(XPath, SlashPos + 1);
        end;
        if (NodeName = string(Self.Document.Root.Name)) or (NodeName = '*') then begin
          if XPath = '' then begin
            Nodes.Add(Self.Document.Root);
          end else begin
            ProcessXPath(Self.Document.Root, XPath, Nodes, True);
          end;
        end else begin
          Result := nil;
        end;
      end else begin
        ProcessXPath(Self, XPath, Nodes, True);
      end;
      if Nodes.Count > 0 then
        Break;
    end;
    if Nodes.Count > 0 then
      Result := TXmlNode(Nodes[0])
    else
      Result := nil;
  finally
    Nodes.Free;
  end;
end {TXmlNodeHelper.SelectNode};

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.CountNodes(const XPath: string): Integer;
begin
  Result := SelectNodes(XPath, nil);
end {TXmlNodeHelper.CountNodes};

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.GetPrefixNamespace(const Prefix: string): string;
var
  NSAttr: string;
begin
  Result := '';
  if not Assigned(Self) then
    Exit;

  if Prefix = '' then begin
    NSAttr := 'xmlns';
  end else begin
    NSAttr := 'xmlns:' + Prefix;
  end;
  if Self.HasAttribute(UTF8String(NSAttr)) then begin
    Result := Self.AttributeByNameWide[UTF8String(NSAttr)];
  end else if not Assigned(Self.Parent) then begin
    if Prefix = '' then
      Result := ''
    else
      raise ENotSupportedException.CreateFmt('No namespace defined for prefix "%s".', [Prefix]);
  end else begin
    Result := Self.Parent.GetPrefixNamespace(Prefix);
  end;
end {TXmlNodeHelper.GetPrefixNamespace};

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.GetNamespace: string;
var
  Name, Prefix: string;
  SepPos: Integer;
begin
  Result := '';
  if not Assigned(Self) then
    Exit;

  // Split prefix and name of the current node
  Name := string(Self.Name);
  SepPos := Pos(':', Name);
  if SepPos = 0 then begin
    Prefix := '';
  end else begin
    Prefix := Copy(Name, 1, SepPos - 1);
    Name := Copy(Name, SepPos + 1);
  end;

  Result := GetPrefixNamespace(Prefix);
end {TXmlNodeHelper.GetNamespace};

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.GetLocalName: string;
var
  Name: string;
  SepPos: Integer;
begin
  Result := '';
  if not Assigned(Self) then
    Exit;

  Name := string(Self.Name);
  SepPos := Pos(':', Name);
  if SepPos = 0 then begin
    Result := '';
  end else begin
    Result := Copy(Name, SepPos + 1);
  end;
end {TXmlNodeHelper.GetLocalName};

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.GetPrefix: string;
var
  Name: string;
  SepPos: Integer;
begin
  Result := '';
  if not Assigned(Self) then
    Exit;

  Name := string(Self.Name);
  SepPos := Pos(':', Name);
  if SepPos = 0 then begin
    Result := Name;
  end else begin
    Result := Copy(Name, 1, SepPos - 1);
  end;
end {TXmlNodeHelper.GetLocalName};

{ ------------------------------------------------------------------------------------------------ }
// Deze functie verwijdert alle nodes die niet bij de opgegeven namespace horen,
//  en verwijdert de prefixes van de nodes die er wel bij horen.
function TXmlNodeHelper.ForceNamespace(const TargetNS: string; const NamespacePrefixes: TStrings = nil): Boolean;
var
  NSP: TStringList;
  SepPos, i: Integer;
  Prefix, Name, NS: string;
begin
  if not Assigned(Self) then
    Exit(False);

  NSP := TStringList.Create;
  try
    NSP.CaseSensitive := True;
    NSP.StrictDelimiter := True;
    NSP.Duplicates := dupError;
    if Assigned(NamespacePrefixes) then begin
      NSP.AddStrings(NamespacePrefixes);
    end;

    // Update the list of name space prefixes, based on the node's xmlns-attributes
    for i := 0 to Self.AttributeCount - 1 do begin
      Name := string(Self.AttributeName[i]);
      if SameStr(Name, 'xmlns') then begin
        NSP.Values[''] := Self.AttributeValueAsUnicodeString[i];
      end else if StartsStr(Name, 'xmlns:') then begin
        Prefix := Copy(Name, 7);
        NSP.Values[Prefix] := Self.AttributeValueAsUnicodeString[i];
      end;
    end;

    // Split prefix and name of the current node
    Name := string(Self.Name);
    SepPos := Pos(':', Name);
    if SepPos = 0 then begin
      Prefix := '';
    end else begin
      Prefix := Copy(Name, 1, SepPos - 1);
      Name := Copy(Name, SepPos + 1);
    end;

    // Update the list of name space prefixes, based on the node's ancestors' xmlns-attributes
    if not Assigned(NamespacePrefixes) and (NSP.IndexOfName(Prefix) = -1) then begin
      NSP.Values[Prefix] := Self.GetPrefixNamespace(Prefix);
    end;

    // Determine this node's namespace
    NS := NSP.Values[Prefix];
    if NS <> TargetNS then begin
      // This node is not in our target namespace, simply delete it;
      //  but if it's the root, then create a new root node...
      if Self = Self.Document.Root then begin
        {--- TODO: Search the document for any node in our target namespace, and make that the root node?  MCO 11-03-2013 ---}
        Self.Delete;
        Self.Document.RootNodeList.NodeAdd(TXmlNode.Create(Self.Document));
      end else begin
        Self.Delete;
      end;
      Result := False;
    end else begin
      // First, force the namespace on all of our child nodes
      for i := 0 to Self.NodeCount - 1 do begin
        Self.Nodes[i].ForceNamespace(TargetNS, NSP);
      end;
      if Prefix <> '' then begin
        // Check if the default namespace is ours; if not, then make it so
        if NSP.Values[''] <> TargetNS then begin
          if not Assigned(Self.Parent) or not Assigned(NamespacePrefixes) then begin
            Self.AttributeByNameWide['xmlns'] := TargetNS;
          end else begin
            i := Self.AttributeIndexByname('xmlns');
            if i <> -1 then
              Self.AttributeDelete(i);
          end;
          NSP.Values[''] := TargetNS;
        end;
        // Now, remove the prefix
        Self.Name := UTF8String(Name);
      end;
      Result := True;
    end;
  finally
    NSP.Free;
  end;
end {TXmlNodeHelper.ForceNamespace};

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.SelectNodes(const XPath: string): TXmlNodeList;
begin
  Result := TXmlNodeList.Create;
  SelectNodes(XPath, Result);
end {TXmlNodeHelper.SelectNodes};

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.SelectNodes(XPath: string; const Nodes: TList): Integer;
var
  Queries: TArray<string>;
  qi: Integer;
  SlashPos: integer;
  NodeName: string;
  DisparateNodes: TXmlNodeList;
  i: Integer;
begin
  Result := 0;
{$IFDEF DEBUG}
  if not Assigned(Self) then
    OutputDebugString('NIL NODE REQUESTED');
{$ENDIF}
  if not Assigned(Self) then
    Exit(0);

  Queries := XPath.Split(['|']);
  for qi := Low(Queries) to High(Queries) do begin
    XPath := Queries[qi];
    if Copy(XPath, 1, 1) = '/' then begin
      XPath := Copy(XPath, 2);
      SlashPos := Pos('/', XPath);
      if SlashPos = 0 then begin
        NodeName := XPath;
        XPath := '';
      end else begin
        NodeName := Copy(XPath, 1, SlashPos - 1);
        XPath := Copy(XPath, SlashPos + 1);
      end;
      if (NodeName = string(Self.Document.Root.Name)) or (NodeName = '*') then begin
        if XPath = '' then begin
          Nodes.Add(Self.Document.Root);
          Result := Result + 1;
        end else begin
          Result := Result + ProcessXPath(Self.Document.Root, XPath, Nodes, False);
        end;
      end else if (NodeName = '') and (XPath <> '') then begin
        {--- MCO 10-08-2012: Het zoekpad bevatte //; we achterhalen nu de naam van de volgende node,
                              en gaan op zoek naar alle nodes die zo heten. ---}
        SlashPos := Pos('/', XPath);
        if SlashPos = 0 then begin
          NodeName := XPath;
          XPath := '';
        end else begin
          NodeName := Copy(XPath, 1, SlashPos - 1);
          XPath := Copy(XPath, SlashPos + 1);
        end;

        DisparateNodes := TXmlNodeList.Create;
        try
          Self.FindNodes(UTF8String(NodeName), DisparateNodes);
          for i := 0 to DisparateNodes.Count - 1 do begin
            Result := Result + ProcessXPath(DisparateNodes[i], XPath, Nodes, False);
          end;
        finally
          DisparateNodes.Free;
        end;
      end;
    end else begin
      Result := Result + ProcessXPath(Self, XPath, Nodes, False);
    end;
  end {for Query};
end {TXmlNodeHelper.SelectNodes};

{ ------------------------------------------------------------------------------------------------ }
procedure TXmlNodeHelper.SetValueAsEnum<T>(const Value: T);
begin
  ValueAsUnicodeString := TEnum<T>.EnumToStr(Value);
end {TXmlNodeHelper.SetValueAsEnum<T>};

{ ------------------------------------------------------------------------------------------------ }
procedure TXmlNodeHelper.SetValueAsEnum<T>(const Value: T; const Names: array of string);
begin
  ValueAsUnicodeString := Names[TEnum<T>.Ord(Value)];
end {TXmlNodeHelper.SetValueAsEnum<T>};

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.WalkSubtree(const Direction: TWalkDirection;
                                    const Filter: TXmlNodeFilter): Boolean;
begin
  Result := WalkSubtree(Direction, High(Cardinal), Filter);
end;
{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.WalkSubtree(const Direction: TWalkDirection;
                                    const Depth: Cardinal;
                                    const Filter: TXmlNodeFilter): Boolean;
var
  i: Integer;
begin
  Result := True;
  if Direction in [wdTopDownFirstToLast, wdTopDownLastToFirst] then begin
    Result := Filter(Self);
    if not Result then
      Exit;
  end;

  if Depth > 0 then begin
    if Direction in [wdTopDownFirstToLast, wdBottomUpFirstToLast] then begin
      for i := 0 to Self.NodeCount - 1 do begin
        Result := Self.Nodes[i].WalkSubtree(Direction, Depth - 1, Filter);
        if not Result then
          Exit;
      end;
    end else begin
      for i := Self.NodeCount - 1 downto 0 do begin
        Result := Self.Nodes[i].WalkSubtree(Direction, Depth - 1, Filter);
        if not Result then
          Exit;
      end;
    end;
  end;

  if Direction in [wdBottomUpFirstToLast, wdBottomUpLastToFirst] then
    Result := Filter(Self);
end {TXmlNodeHelper.WalkSubtree};

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.GetXML: string;
begin
{$IFDEF DEBUG}
  if not Assigned(Self) then
    OutputDebugString('NIL NODE REQUESTED');
{$ENDIF}
  if Assigned(Self) then
    Result := string(Self.WriteToString)
  else
    Result := '';
end {TXmlNodeHelper.GetXML};

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeHelper.HasChildNode(const Name: string): Boolean;
begin
{$IFDEF DEBUG}
  if not Assigned(Self) then
    OutputDebugString('NIL NODE REQUESTED');
{$ENDIF}
  if Assigned(Self) then
    Result := Self.NodeIndexByName(UTF8String(Name)) <> -1
  else
    Result := False;
end {TXmlNodeHelper.HasChild};



{ ================================================================================================ }
{ TNativeXmlHelper }

{ ------------------------------------------------------------------------------------------------ }
function TNativeXmlHelper.CountNodes(const XPath: string): Integer;
begin
{$IFDEF DEBUG}
  if not Assigned(Self) then
    OutputDebugString('NIL NODE REQUESTED');
{$ENDIF}
  if Assigned(Self) then
    Result := Self.Root.CountNodes(XPath)
  else
    Result := 0;
end {TNativeXmlHelper.CountNodes};

{ ------------------------------------------------------------------------------------------------ }
function TNativeXmlHelper.SelectNode(const XPath: string): TXmlNode;
begin
{$IFDEF DEBUG}
  if not Assigned(Self) then
    OutputDebugString('NIL NODE REQUESTED');
{$ENDIF}
  if Assigned(Self) then
    Result := Self.Root.SelectNode(XPath)
  else
    Result := nil;
end {TNativeXmlHelper.SelectNode};

{ ------------------------------------------------------------------------------------------------ }
function TNativeXmlHelper.SelectNodes(const XPath: string): TXmlNodeList;
begin
{$IFDEF DEBUG}
  if not Assigned(Self) then
    OutputDebugString('NIL NODE REQUESTED');
{$ENDIF}
  if Assigned(Self) then
    Result := Self.Root.SelectNodes(XPath)
  else
    Result := TXmlNodeList.Create;
end {TNativeXmlHelper.SelectNodes};

{ ------------------------------------------------------------------------------------------------ }
function TNativeXmlHelper.SelectNodes(const XPath: string; const Nodes: TList): Integer;
begin
{$IFDEF DEBUG}
  if not Assigned(Self) then
    OutputDebugString('NIL NODE REQUESTED');
{$ENDIF}
  if Assigned(Self) then
    Result := Self.Root.SelectNodes(XPath, Nodes)
  else
    Result := 0;
end {TNativeXmlHelper.SelectNodes};


{ ================================================================================================ }
{ TXmlNodeListHelper.TXmlNodeListEnumerator }

{ ------------------------------------------------------------------------------------------------ }
constructor TXmlNodeListHelper.TXmlNodeListEnumerator.Create(const List: TXmlNodeList);
begin
  inherited Create;
  FList := List;
  FIndex := -1;
end {TXmlNodeListHelper.TXmlNodeListEnumerator.Create};

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeListHelper.TXmlNodeListEnumerator.GetCurrent: TXmlNode;
begin
  Result := FList.Items[FIndex];
end {TXmlNodeListHelper.TXmlNodeListEnumerator.GetCurrent};

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeListHelper.TXmlNodeListEnumerator.MoveNext: Boolean;
begin
  Inc(FIndex);
  Result := FIndex < FList.Count;
end {TXmlNodeListHelper.TXmlNodeListEnumerator.MoveNext};


{ ================================================================================================ }
{ TXmlNodeListHelper }

{ ------------------------------------------------------------------------------------------------ }
function TXmlNodeListHelper.GetEnumerator: TXmlNodeListEnumerator;
begin
  Result := TXmlNodeListEnumerator.Create(Self);
end {TXmlNodeListHelper.GetEnumerator};

end.

Added src/SimpleGenericEnum.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
unit SimpleGenericEnum;

interface
uses SysUtils,TypInfo;
type
  TEnum<T> = record
  type
    EEnum= class(Exception)
      constructor CreateFmt(const Test: String; const Args: array of Const);
    end;
  public
    Value:T;
    class var _TypeData: pTypeData;
    class function High: T; static;
    class function Low: T; static;
    class function GetTypeData: pTypeData; inline; static;{Inline working is a wish really}
    class operator Implicit(aValue: Integer): TEnum<T>;
    class operator Implicit(aValue: TEnum<T>): Integer;
    class operator Implicit(aValue: T): TEnum<T>;
    class operator Implicit(aValue: TEnum<T>): T;
    class operator Implicit(const aValue: String): TEnum<T>;
    class operator Implicit(aValue: TEnum<T>): String;
    class function GetEnumValue(const Name: String): Integer; inline; static;
    class function GetEnumName(Index: Integer): String; overload; inline; static;
    class function GetEnumName(Index: T): String; overload;inline; static;
    class function Ord(Value:T): Integer; overload; inline; static;{Inline working is a wish really}
    class function Cast(Value:Integer): T; inline; static; {Inline working is a wish really}
    function ToString: String;
    function StringTo(const AValue: String): Boolean;
    function Ord(): Integer; overload; inline;
  public
    // These function determine the default format of the strings
    // Currenlty they remove the lower case prefix and convert '_' to ' ' and vice verse
    class function EnumToStr(Value: T): String; static;
    class function StrToEnum(Name: String; out Value: T): Boolean; static;
  end;

implementation
{ TEnum<T> }


class operator TEnum<T>.Implicit(aValue: TEnum<T>): T;
begin
  Result := aValue.Value;
end;

class operator TEnum<T>.Implicit(aValue: T): TEnum<T>;
begin
  Result.Value := aValue;
end;

class operator TEnum<T>.Implicit(const aValue: String): TEnum<T>;
begin
  if not Result.StringTo(aValue) then
    raise EEnum.CreateFmt('"%s" is not a valid name',[aValue]);
end;

class function TEnum<T>.Cast(Value: Integer): T;
begin
  if (Value < GetTypeData.MinValue) then
    raise EEnum.CreateFmt('%d is below min value [%d]',[Value,GetTypeData.MinValue])
  else if (Value > GetTypeData.MaxValue) then
    raise EEnum.CreateFmt('%d is above max value [%d]',[Value,GetTypeData.MaxValue]);
  case Sizeof(T) of
    1: pByte(@Result)^ := Value;
    2: pWord(@Result)^ := Value;
    4: pCardinal(@Result)^ := Value;
  end;
end;

class function TEnum<T>.GetEnumName(Index: Integer): String;
begin
  Result := TypInfo.GetEnumName(TypeInfo(T),Index);
end;


class function TEnum<T>.GetEnumName(Index: T): String;
begin
  Result := GetEnumName(Ord(Index));
end;

class function TEnum<T>.GetEnumValue(const Name: String): Integer;
begin
  Result := TypInfo.GetEnumValue(TypeInfo(T),Name);
end;


class function TEnum<T>.GetTypeData: pTypeData;
begin
  if not Assigned(_TypeData) then
    _TypeData := TypInfo.GetTypeData(TypeInfo(T));
  Result := _TypeData;
end;

class function TEnum<T>.High: T;
begin
  Result := Cast(GetTypeData.MaxValue);
end;

class operator TEnum<T>.Implicit(aValue: TEnum<T>): String;
begin
  Result := aValue.ToString;
end;

class function TEnum<T>.Low: T;
begin
  Result := Cast(GetTypeData.MinValue);
end;

class operator TEnum<T>.Implicit(aValue: Integer): TEnum<T>;
begin
  Result.Value := Cast(aValue);
end;

class operator TEnum<T>.Implicit(aValue: TEnum<T>): Integer;
begin
  Result := Ord(aValue.Value);
end;

class function TEnum<T>.Ord(Value: T): Integer;
begin
  case Sizeof(T) of
    1: Result := pByte(@Value)^;
    2: Result := pWord(@Value)^;
    4: Result := pCardinal(@Value)^;
  end;
end;

function TEnum<T>.Ord: Integer;
begin
  Result := Ord(Value);
end;

function TEnum<T>.StringTo(const AValue: String): Boolean;
begin
  Result := StrToEnum(AValue,Value);
end;

class function TEnum<T>.StrToEnum(Name: String; out Value: T): Boolean;
var
  Temp: String;
  Index: Integer;
begin
  Index := GetEnumValue(Name);
  if Index < 0 then begin
    Temp := GetEnumName(Ord(Low));
    Index := 0;
    while (Index < Length(Temp)) and CharInSet(Temp[Index+1], ['a'..'z']) do
      Inc(Index);
    SetLength(Temp,Index);
    Temp := Temp+Name;
    Index := 1;
    while (Index <= Length(Temp)) do begin
      if (Temp[Index] = ' ')  then
        Temp[Index] := '_';
      Inc(Index);
    end;
    Index := GetEnumValue(Temp);
  end;
  Result := Index >= 0;
  if Result then
    Value := Cast(Index);
end;

class function TEnum<T>.EnumToStr(Value: T): String;
var Index: Integer;
begin
  Result := GetEnumName(Value);
  while (Length(Result) > 0) and CharInSet(Result[1], ['a'..'z']) do
    Delete(Result,1,1);
  for Index := 1 to Length(Result) do
    if Result[Index] = '_' then
      Result[Index] := ' ';
end;

function TEnum<T>.ToString: String;
begin
  Result := EnumToStr(Value);
end;

{ TEnum<T>.EEnum }

constructor TEnum<T>.EEnum.CreateFmt(const Test: String;
  const Args: array of Const);
var
  Info: pTypeInfo;
begin
  Info := TypeInfo(T);
  inherited CreateFmt('TEnum<%s>:%s',[Info.Name,Format(Test,Args)]);
end;

end.

Added src/U_AutoUpdate.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
unit U_AutoUpdate;

interface
uses
  Classes;

type
  TAutoUpdateThread = class(TThread)
  public
    procedure Execute; override;
  end;

implementation
uses
  System.SysUtils, System.IOUtils, System.Zip,
  System.RegularExpressions, System.Character,
  L_HttpClient, L_VersionInfoW,
  NativeXml, NativeXmlXPath;


{ ---------------------------------------------------------------------------- }
function Download(const URL: string; const ResponseHeaders: TStrings = nil): TStream;
var
  HttpClient: THttpClient;
begin
  HttpClient := THttpClient.Create(URL);
  try
    if HttpClient.Get() = 200 then begin
      Result := TMemoryStream.Create;
      Result.CopyFrom(HttpClient.ResponseStream, 0);
    end else begin
      Result := nil;
      raise EHttpError.CreateFmt('%d %s', [HttpClient.StatusCode, HttpClient.StatusText]);
    end;
    if Assigned(ResponseHeaders) then
      ResponseHeaders.AddStrings(HttpClient.ResponseHeaders);
  finally
    HttpClient.Free;
  end;
end {Download};

{ ---------------------------------------------------------------------------- }
function CompareVersions(A, B: string): Integer;
  { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
  function ExtractNumber(var S: string): Integer;
  var
    ErrPos: integer;
  begin
    Result := 0;
    while (Length(S) > 0) and not S[1].IsDigit do
      Delete(S, 1, 1);
    if S = '' then
      Exit;
    Val(S, Result, ErrPos);
    case ErrPos of
      0, 1: S := '';
      else  S := Copy(S, ErrPos);
    end;
  end {ExtractNumber};
  { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
var
  iA, iB: Integer;
begin
  repeat
    iA := ExtractNumber(A);
    iB := ExtractNumber(B);
    if iA < iB then
      Exit(-1)
    else if iA > iB then
      Exit(1)
  until (A = '') and (B = '');
  Exit(0);
end {CompareVersions};



{ TAutoUpdateThread }

{ ---------------------------------------------------------------------------- }
procedure TAutoUpdateThread.Execute;
var
  Stream: TStream;
  xmlDoc: TNativeXml;
  xmlItems: TXmlNodeList;
  xmlItem: TXmlNode;
  LatestVersion, OwnVersion: string;
  CurrentExe, CurrentExePath, BackupExe: string;
  rexVersion: System.RegularExpressions.TRegEx;
  Match: TMatch;
  Zip: TZipFile;
  i: Integer;
begin
  xmlDoc := TNativeXml.Create;
  try
    Stream := Download('http://fossil.2of4.net/simple_date_ss/timeline.rss?y=ci&tag=publish');
    try
      xmlDoc.LoadFromStream(Stream);
    finally
      Stream.Free;
    end;
    xmlItems := xmlDoc.SelectNodes('/rss/channel/item/title');
    try
      rexVersion.Create('(\d\.)+\d', [roCompiled]);
      LatestVersion := '';
      for xmlItem in xmlItems do begin
        Match := rexVersion.Match(xmlItem.AsString);
        if Match.Success then begin
          LatestVersion := Match.Groups[0].Value;
          Break;
        end;
        if LatestVersion = '' then exit;
      end{for};
    finally
      xmlItems.Free;
    end;
  finally
    xmlDoc.Free;
  end;
  CurrentExe := ParamStr(0);
  with TFileVersionInfo.Create(CurrentExe) do begin
    OwnVersion := FileVersion;
    Free;
  end;
  if CompareVersions(LatestVersion, OwnVersion) > 0 then begin
    Stream := Download('http://fossil.2of4.net/simple_date_ss/zip/ss_datum.zip?uuid=publish');
    try
      CurrentExePath := TPath.GetDirectoryName(CurrentExe);
      Zip := TZipFile.Create;
      try
        Zip.Open(Stream, zmRead);
        for i := 0 to Zip.FileCount - 1 do begin
          try
            if SameFileName(TPath.GetFileName(Zip.FileName[i]), TPath.GetFileName(CurrentExe)) then begin
              BackupExe := ChangeFileExt(CurrentExe, '_v' + ownVersion + ExtractFileExt(CurrentExe));
              TFile.Move(CurrentExe, BackupExe);
            end;
            Zip.Extract(i, CurrentExePath, False);
          except
            // TODO: what to do with the exception?
          end;
        end;
      finally
        Zip.Free;
      end;
    finally
      Stream.Free;
    end;
  end{if};
end {TAutoUpdateThread.Execute};

end.

Changes to src/ssdatum.dpr.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
..
31
32
33
34
35
36
37
38
39
40
41
42
program ssdatum;

uses
  WinApi.Windows,
  Vcl.Forms,
  F_Main in 'F_Main.pas' {frmMain},
  SingleInstance in 'SingleInstance.pas',
  ScreenSaverUtils in 'ScreenSaverUtils.pas'(*,
  F_Config in 'F_Config.pas' {frmConfig}*);

{$R *.res}

begin
{$IFDEF DEBUG}
  ReportMemoryLeaksOnShutdown := True;
................................................................................

//  if ScreenSaverMode = ssConfigure then begin
//    // Create the configure form to configure the screen saver
//    Application.CreateForm(TfrmConfig, frmConfig);
//  end else begin
    // We are either doing a preview or actually running the screen saver
    Application.CreateForm(TfrmMain, frmMain);
    frmMain.Left := Screen.PrimaryMonitor.Left;
    frmMain.WindowState := wsMaximized;
//  end;
  Application.Run;
end.







|







 







|




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
..
31
32
33
34
35
36
37
38
39
40
41
42
program ssdatum;

uses
  WinApi.Windows,
  Vcl.Forms,
  F_Main in 'F_Main.pas' {frmMain},
  SingleInstance in 'SingleInstance.pas',
  ScreenSaverUtils in 'ScreenSaverUtils.pas' (*,
  F_Config in 'F_Config.pas' {frmConfig}*);

{$R *.res}

begin
{$IFDEF DEBUG}
  ReportMemoryLeaksOnShutdown := True;
................................................................................

//  if ScreenSaverMode = ssConfigure then begin
//    // Create the configure form to configure the screen saver
//    Application.CreateForm(TfrmConfig, frmConfig);
//  end else begin
    // We are either doing a preview or actually running the screen saver
    Application.CreateForm(TfrmMain, frmMain);
  frmMain.Left := Screen.PrimaryMonitor.Left;
    frmMain.WindowState := wsMaximized;
//  end;
  Application.Run;
end.

Changes to src/ssdatum.dproj.

42
43
44
45
46
47
48


49
50
51
52
53
54
55
...
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
    <PropertyGroup Condition="('$(Platform)'=='Win32' and '$(Cfg_2)'=='true') or '$(Cfg_2_Win32)'!=''">
        <Cfg_2_Win32>true</Cfg_2_Win32>
        <CfgParent>Cfg_2</CfgParent>
        <Cfg_2>true</Cfg_2>
        <Base>true</Base>
    </PropertyGroup>
    <PropertyGroup Condition="'$(Base)'!=''">


        <VerInfo_Release>1</VerInfo_Release>
        <SanitizedProjectName>ssdatum</SanitizedProjectName>
        <DCC_SYMBOL_PLATFORM>false</DCC_SYMBOL_PLATFORM>
        <VerInfo_Locale>1043</VerInfo_Locale>
        <DCC_Namespace>System;Xml;Data;Datasnap;Web;Soap;Vcl;Vcl.Imaging;Vcl.Touch;Vcl.Samples;Vcl.Shell;$(DCC_Namespace)</DCC_Namespace>
        <Manifest_File>$(BDS)\bin\default_app.manifest</Manifest_File>
        <DCC_UNIT_PLATFORM>false</DCC_UNIT_PLATFORM>
................................................................................
        <Borland.ProjectType/>
        <BorlandProject>
            <Delphi.Personality>
                <Source>
                    <Source Name="MainSource">ssdatum.dpr</Source>
                </Source>
                <Excluded_Packages>
                    <Excluded_Packages Name="$(BDSBIN)\dcloffice2k190.bpl">Microsoft Office 2000 Sample Automation Server Wrapper Components</Excluded_Packages>
                    <Excluded_Packages Name="$(BDSBIN)\dclofficexp190.bpl">Microsoft Office XP Sample Automation Server Wrapper Components</Excluded_Packages>
                </Excluded_Packages>
                <VersionInfo>
                    <VersionInfo Name="IncludeVerInfo">False</VersionInfo>
                    <VersionInfo Name="AutoIncBuild">False</VersionInfo>
                    <VersionInfo Name="MajorVer">1</VersionInfo>
                    <VersionInfo Name="MinorVer">0</VersionInfo>
                    <VersionInfo Name="Release">0</VersionInfo>







>
>







 







|
|







42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
...
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
    <PropertyGroup Condition="('$(Platform)'=='Win32' and '$(Cfg_2)'=='true') or '$(Cfg_2_Win32)'!=''">
        <Cfg_2_Win32>true</Cfg_2_Win32>
        <CfgParent>Cfg_2</CfgParent>
        <Cfg_2>true</Cfg_2>
        <Base>true</Base>
    </PropertyGroup>
    <PropertyGroup Condition="'$(Base)'!=''">
        <Icon_MainIcon>ssdatum.ico</Icon_MainIcon>
        <DCC_UnitSearchPath>NativeXml;$(DCC_UnitSearchPath)</DCC_UnitSearchPath>
        <VerInfo_Release>1</VerInfo_Release>
        <SanitizedProjectName>ssdatum</SanitizedProjectName>
        <DCC_SYMBOL_PLATFORM>false</DCC_SYMBOL_PLATFORM>
        <VerInfo_Locale>1043</VerInfo_Locale>
        <DCC_Namespace>System;Xml;Data;Datasnap;Web;Soap;Vcl;Vcl.Imaging;Vcl.Touch;Vcl.Samples;Vcl.Shell;$(DCC_Namespace)</DCC_Namespace>
        <Manifest_File>$(BDS)\bin\default_app.manifest</Manifest_File>
        <DCC_UNIT_PLATFORM>false</DCC_UNIT_PLATFORM>
................................................................................
        <Borland.ProjectType/>
        <BorlandProject>
            <Delphi.Personality>
                <Source>
                    <Source Name="MainSource">ssdatum.dpr</Source>
                </Source>
                <Excluded_Packages>
                    <Excluded_Packages Name="$(BDSBIN)\dcloffice2k200.bpl">Microsoft Office 2000 Sample Automation Server Wrapper Components</Excluded_Packages>
                    <Excluded_Packages Name="$(BDSBIN)\dclofficexp200.bpl">Microsoft Office XP Sample Automation Server Wrapper Components</Excluded_Packages>
                </Excluded_Packages>
                <VersionInfo>
                    <VersionInfo Name="IncludeVerInfo">False</VersionInfo>
                    <VersionInfo Name="AutoIncBuild">False</VersionInfo>
                    <VersionInfo Name="MajorVer">1</VersionInfo>
                    <VersionInfo Name="MinorVer">0</VersionInfo>
                    <VersionInfo Name="Release">0</VersionInfo>