Debian Codegraph @

src/files/castlexmlutils.pas

raw
1 {
2 Copyright 2012-2018 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { XML utilities.
17
18 This unit provides a lot of comfortable routines and helpers to manipulate
19 XML files. It builds on top of FPC DOM unit, and you can still use
20 the full power of FPC DOM unit, however we provide helpers to do a lot
21 of things easier.
22
23 The engine example application that manipulates XML files is inside
24 examples/short_api_samples/xml_utils/ . This is the code that loads and saves XML:
25
26 @includeCode(../../examples/short_api_samples/xml_utils/mybookmarks.pas)
27 }
28 unit CastleXmlUtils;
29
30 {$I castleconf.inc}
31
32 interface
33
34 uses SysUtils, DOM, CastleDownload,
35 CastleUtils, CastleColors, CastleVectors;
36
37 type
38 EDOMAttributeMissing = class(Exception);
39 EDOMChildElementError = class(Exception);
40
41 TXMLElementIterator = class;
42
43 TDOMNodeHelper = class helper for TDOMNode
44 private
45 function GetNodeValue8: String;
46 procedure SetNodeValue8(const S: String);
47 public
48 { Node name (attribute, element or such name).
49
50 In FPC this is expressed as an 8-bit string (in UTF-8 encoding),
51 contrary to the NodeName from FPC DOM unit that is a WideString (DOMString). }
52 function NodeName8: String;
53
54 { Node value (like an attribute value).
55
56 In FPC this is expressed as an 8-bit string (in UTF-8 encoding),
57 contrary to the NodeValue from FPC DOM unit that is a WideString (DOMString). }
58 property NodeValue8: String read GetNodeValue8 write SetNodeValue8;
59 end;
60
61 TDOMCharacterDataHelper = class helper for TDOMCharacterData
62 { String data.
63
64 In FPC this is expressed as an 8-bit string (in UTF-8 encoding),
65 contrary to the Data from FPC DOM unit that is a WideString (DOMString). }
66 function Data8: String;
67 end;
68
69 TDOMElementHelper = class helper for TDOMElement
70 public
71
72 { ------------------------------------------------------------------------
73 Get an optional attribute to a "var" parameter, returns if found. }
74
75 {$ifdef FPC}
76 { Read from Element attribute value and returns @true,
77 or (if there is no such attribute) returns @false
78 and does not modify Value. Value is a "var", not "out" param,
79 because in the latter case it's guaranteed that the old Value
80 will not be cleared.
81
82 Note that the returned Value may be empty, even when this returns @true,
83 if the value is explicitly set to empty in XML (by @code(xxx="") in XML). }
84 function AttributeString(const AttrName: String; var Value: String): boolean; overload;
85 {$endif}
86
87 { Read from Element attribute value as URL and returns @true,
88 or (if there is no such attribute) returns @false
89 and does not modify Value.
90
91 Returned URL is always absolute. The value in file may be a relative URL,
92 it is resolved with respect to BaseUrl, that must be absolute. }
93 function AttributeUrl(const AttrName: String; const BaseUrl: String; var Url: String): boolean; overload;
94
95 { Read from Element attribute value as Cardinal and returns @true,
96 or (if there is no such attribute) returns @false
97 and does not modify Value. }
98 function AttributeCardinal(const AttrName: String; var Value: Cardinal): boolean; overload;
99
100 { Read from Element attribute value as Integer and returns @true,
101 or (if there is no such attribute) returns @false
102 and does not modify Value. }
103 function AttributeInteger(const AttrName: String; var Value: Integer): boolean; overload;
104
105 { Read from Element attribute value as Int64 and returns @true,
106 or (if there is no such attribute) returns @false
107 and does not modify Value. }
108 function AttributeInt64(const AttrName: String; var Value: Int64): boolean; overload;
109
110 { Read from Element attribute value as QWord and returns @true,
111 or (if there is no such attribute) returns @false
112 and does not modify Value. }
113 function AttributeQWord(const AttrName: String; var Value: QWord): boolean; overload;
114
115 { Read from Element attribute value as Single and returns @true,
116 or (if there is no such attribute) returns @false
117 and does not modify Value. }
118 function AttributeSingle(const AttrName: String; var Value: Single): boolean; overload;
119
120 { Read from Element attribute value as Float and returns @true,
121 or (if there is no such attribute) returns @false
122 and does not modify Value.
123
124 Note: for powerful reading of float expressions,
125 consider using @code(AttributeFloatExpression) instead of @code(AttributeFloat).
126 It can read expressions like @code("3.0 * 2.0") or @code("sin(2.0)").
127 Use CastleScriptXML unit to introduce
128 necessary class helper for this, see @link(TDOMElementScriptHelper.AttributeFloatExpression). }
129 function AttributeFloat(const AttrName: String; var Value: Float): boolean; overload;
130
131 { Read from Element attribute value as Boolean and returns @true,
132 or (if there is no such attribute) returns @false
133 and does not modify Value.
134
135 A boolean value is interpreted just like FPC's TXMLConfig
136 objects: true is designated by word @code(true), false by word
137 @code(false), case is ignored.
138 If attribute exists but it's value
139 is not @code(true) or @code(false), then returns @false and doesn't
140 modify Value paramater. So behaves just like the attribute didn't exist. }
141 function AttributeBoolean(const AttrName: String; var Value: boolean): boolean; overload;
142
143 { Read from Element attribute value as color and returns @true,
144 or (if there is no such attribute) returns @false
145 and does not modify Value.
146
147 This can read a color value in any of these formats:
148
149 @unorderedList(
150 @item(Hexadecimal format, like set by @link(AttributeColorSet).)
151
152 @item(4D vector format, with 4 vector components in range 0..1,
153 separated by whitespace.
154 Like set by @link(AttributeSet AttributeSet(TVector4)) overload.)
155 )
156
157 In effect, you can write TCastleColor values to XML using
158 @link(AttributeSet) or @link(AttributeColorSet), they both can be read back
159 using this method. }
160 function AttributeColor(const AttrName: String; var Value: TCastleColor): Boolean; overload;
161
162 { Read from Element attribute value as RGB color and returns @true,
163 or (if there is no such attribute) returns @false
164 and does not modify Value.
165
166 This can read a color value in any of these formats:
167
168 @unorderedList(
169 @item(Hexadecimal format, like set by @link(AttributeColorSet).)
170
171 @item(3D vector format, with 3 vector components in range 0..1,
172 separated by whitespace.
173 Like set by @link(AttributeSet AttributeSet(TVector3)) overload.)
174 )
175
176 In effect, you can write TCastleColorRGB values to XML using
177 @link(AttributeSet) or @link(AttributeColorSet), they both can be read back
178 using this method. }
179 function AttributeColorRGB(const AttrName: String; var Value: TCastleColorRGB): Boolean; overload;
180
181 { Read from Element attribute as a 2D vector (2 floats), and returns @true,
182 or (if there is no such attribute) returns @false
183 and does not modify Value.
184
185 @raises EConvertError If the attribute exists in XML, but has invalid format. }
186 function AttributeVector2(const AttrName: String; var Value: TVector2): boolean; overload;
187
188 { Read from Element attribute as a 3D vector (3 floats), and returns @true,
189 or (if there is no such attribute) returns @false
190 and does not modify Value.
191
192 @raises EConvertError If the attribute exists in XML, but has invalid format. }
193 function AttributeVector3(const AttrName: String; var Value: TVector3): boolean; overload;
194
195 { Read from Element attribute as a 4D vector(4 floats, e.g. rotation), and returns @true,
196 or (if there is no such attribute) returns @false
197 and does not modify Value.
198
199 @raises EConvertError If the attribute exists in XML, but has invalid format. }
200 function AttributeVector4(const AttrName: String; var Value: TVector4): boolean; overload;
201
202 { ------------------------------------------------------------------------
203 Get a required attribute, returns value (exception if not found). }
204
205 { Retrieves from Element given attribute as a string,
206 raises EDOMAttributeMissing if missing.
207
208 Note that the attribute is required, but it's value may still be empty
209 if it's explicitly set to empty in XML (by @code(xxx="") in XML).
210 This is different than TCastleConfig.GetStringNonEmpty method,
211 that serves a similar purpose for TCastleConfig, but it requires
212 @italic(non-empty value) exists. Here, we only require that the value
213 exists, but it may still be empty.
214
215 @raises EDOMAttributeMissing }
216 function AttributeString(const AttrName: String): String; overload;
217
218 { Retrieves from Element given attribute as an absolute URL,
219 raises EDOMAttributeMissing if missing.
220 Returned URL is always absolute. The value in file may be a relative URL,
221 it is resolved with respect to BaseUrl, that must be absolute.
222 @raises EDOMAttributeMissing }
223 function AttributeUrl(const AttrName: String; const BaseUrl: String): String; overload;
224
225 { Retrieves from Element given attribute as a Cardinal,
226 raises EDOMAttributeMissing if missing.
227 @raises EDOMAttributeMissing }
228 function AttributeCardinal(const AttrName: String): Cardinal; overload;
229
230 { Retrieves from Element given attribute as an Integer,
231 raises EDOMAttributeMissing if missing.
232 @raises EDOMAttributeMissing }
233 function AttributeInteger(const AttrName: String): Integer; overload;
234
235 { Retrieves from Element given attribute as an Int64,
236 raises EDOMAttributeMissing if missing.
237 @raises EDOMAttributeMissing }
238 function AttributeInt64(const AttrName: String): Int64; overload;
239
240 { Retrieves from Element given attribute as an QWord,
241 raises EDOMAttributeMissing if missing.
242 @raises EDOMAttributeMissing }
243 function AttributeQWord(const AttrName: String): QWord; overload;
244
245 { Retrieves from Element given attribute as a Single,
246 raises EDOMAttributeMissing if missing.
247 @raises EDOMAttributeMissing }
248 function AttributeSingle(const AttrName: String): Single; overload;
249
250 { Retrieves from Element given attribute as a Float,
251 raises EDOMAttributeMissing if missing.
252
253 Note: for powerful reading of float expressions,
254 consider using @code(AttributeFloatExpression) instead of @code(AttributeFloat).
255 It can read expressions like @code("3.0 * 2.0") or @code("sin(2.0)").
256 Use CastleScriptXML unit to introduce
257 necessary class helper for this, see @link(TDOMElementScriptHelper.AttributeFloatExpression).
258
259 @raises EDOMAttributeMissing }
260 function AttributeFloat(const AttrName: String): Float; overload;
261
262 { Retrieves from Element given attribute as a boolean,
263 raises EDOMAttributeMissing if missing or has invalid value.
264 A boolean value is interpreted just like FPC's TXMLConfig
265 objects: true is designated by word @code(true), false by word
266 @code(false), case is ignored.
267
268 If attribute exists but it's value
269 is not @code(true) or @code(false), then raises EDOMAttributeMissing.
270 So behaves just like the attribute didn't exist.
271
272 @raises EDOMAttributeMissing }
273 function AttributeBoolean(const AttrName: String): boolean; overload;
274
275 { Retrieves from Element given attribute as a color,
276 raises EDOMAttributeMissing if missing or has invalid format.
277 @raises EDOMAttributeMissing }
278 function AttributeColor(const AttrName: String): TCastleColor; overload;
279
280 { Retrieves from Element given attribute as an RGB color,
281 raises EDOMAttributeMissing if missing or has invalid format.
282 @raises EDOMAttributeMissing }
283 function AttributeColorRGB(const AttrName: String): TCastleColorRGB; overload;
284
285 { Retrieves from Element given attribute as a 2D vector (2 floats),
286 raises EDOMAttributeMissing if missing or has invalid format.
287 @raises EDOMAttributeMissing }
288 function AttributeVector2(const AttrName: String): TVector2; overload;
289
290 { Retrieves from Element given attribute as a 3D vector (3 floats),
291 raises EDOMAttributeMissing if missing or has invalid format.
292 @raises EDOMAttributeMissing }
293 function AttributeVector3(const AttrName: String): TVector3; overload;
294
295 { Retrieves from Element given attribute as a 4D vector (4 floats, e.g. rotation),
296 raises EDOMAttributeMissing if missing or has invalid format.
297 @raises EDOMAttributeMissing }
298 function AttributeVector4(const AttrName: String): TVector4; overload;
299
300 { ------------------------------------------------------------------------
301 Get an optional attribute, returns attribute or a default value. }
302
303 { Retrieves from Element given attribute as a string, or a default value
304 if the attribute was not explicitly given. }
305 function AttributeStringDef(const AttrName: String; const DefaultValue: String): String;
306
307 { Retrieves from Element given attribute as a Cardinal, or a default value. }
308 function AttributeCardinalDef(const AttrName: String; const DefaultValue: Cardinal): Cardinal;
309
310 { Retrieves from Element given attribute as an Integer, or a default value. }
311 function AttributeIntegerDef(const AttrName: String; const DefaultValue: Integer): Integer;
312
313 { Retrieves from Element given attribute as an Int64, or a default value. }
314 function AttributeInt64Def(const AttrName: String; const DefaultValue: Int64): Int64;
315
316 { Retrieves from Element given attribute as an QWord, or a default value. }
317 function AttributeQWordDef(const AttrName: String; const DefaultValue: QWord): QWord;
318
319 { Retrieves from Element given attribute as a Single, or a default value. }
320 function AttributeSingleDef(const AttrName: String; const DefaultValue: Single): Single;
321
322 { Retrieves from Element given attribute as a Float, or a default value.
323
324 Note: for powerful reading of float expressions,
325 consider using @code(AttributeFloatExpressionDef) instead of @code(AttributeFloatDef).
326 It can read expressions like @code("3.0 * 2.0") or @code("sin(2.0)").
327 Use CastleScriptXML unit to introduce
328 necessary class helper for this, see @link(TDOMElementScriptHelper.AttributeFloatExpressionDef). }
329 function AttributeFloatDef(const AttrName: String; const DefaultValue: Float): Float;
330
331 { Retrieves from Element given attribute as a boolean,
332 returns a default value if missing or has invalid value. }
333 function AttributeBooleanDef(const AttrName: String; const DefaultValue: boolean): boolean;
334
335 { Retrieves from Element given attribute as a color, or a default value. }
336 function AttributeColorDef(const AttrName: String; const DefaultValue: TCastleColor): TCastleColor;
337
338 { Retrieves from Element given attribute as an RGB color, or a default value. }
339 function AttributeColorRGBDef(const AttrName: String; const DefaultValue: TCastleColorRGB): TCastleColorRGB;
340
341 { Retrieves from Element given attribute as a 2D vector (2 floats), or a default value.
342 @raises EConvertError If the value exists in XML, but has invalid format. }
343 function AttributeVector2Def(const AttrName: String; const DefaultValue: TVector2): TVector2;
344
345 { Retrieves from Element given attribute as a 3D vector (3 floats), or a default value.
346 @raises EConvertError If the value exists in XML, but has invalid format. }
347 function AttributeVector3Def(const AttrName: String; const DefaultValue: TVector3): TVector3;
348
349 { Retrieves from Element given attribute as a 4D vector (4 floats), or a default value.
350 @raises EConvertError If the value exists in XML, but has invalid format. }
351 function AttributeVector4Def(const AttrName: String; const DefaultValue: TVector4): TVector4;
352
353 { Attribute setting ------------------------------------------------------ }
354
355 { Set the attribute as string. Equivalent to standard SetAttribute in DOM unit,
356 but provided here for consistency with other AttributeSet overloads. }
357 procedure AttributeSet(const AttrName: String; const Value: String); overload;
358
359 { Set the attribute as boolean,
360 such that it's readable back by @link(AttributeBoolean) and @link(AttributeBooleanDef). }
361 procedure AttributeSet(const AttrName: String; const Value: boolean); overload;
362
363 { Set the attribute as Integer,
364 such that it's readable back by @link(AttributeInteger) and @link(AttributeIntegerDef). }
365 procedure AttributeSet(const AttrName: String; const Value: Integer); overload;
366
367 { Set the attribute as Int64,
368 such that it's readable back by @link(AttributeInt64) and @link(AttributeInt64Def). }
369 procedure AttributeSet(const AttrName: String; const Value: Int64); overload;
370
371 { Set the attribute as QWord,
372 such that it's readable back by @link(AttributeQWord) and @link(AttributeQWordDef). }
373 procedure AttributeSet(const AttrName: String; const Value: QWord); overload;
374
375 { Set the attribute as Cardinal,
376 such that it's readable back by @link(AttributeCardinal) and @link(AttributeCardinalDef). }
377 procedure AttributeSet(const AttrName: String; const Value: Cardinal); overload;
378
379 { Set the attribute as Single,
380 such that it's readable back by @link(AttributeSingle) and @link(AttributeSingleDef). }
381 procedure AttributeSet(const AttrName: String; const Value: Single); overload;
382
383 { Set the attribute as TVector2,
384 such that it's readable back by @link(AttributeVector2) and @link(AttributeVector2Def). }
385 procedure AttributeSet(const AttrName: String; const Value: TVector2); overload;
386
387 { Set the attribute as TVector3,
388 such that it's readable back by @link(AttributeVector3) and @link(AttributeVector3Def). }
389 procedure AttributeSet(const AttrName: String; const Value: TVector3); overload;
390
391 { Set the attribute as TVector4,
392 such that it's readable back by @link(AttributeVector4) and @link(AttributeVector4Def). }
393 procedure AttributeSet(const AttrName: String; const Value: TVector4); overload;
394
395 { Set the attribute as TCastleColor converted to HEX string,
396 such that it's readable back by @link(AttributeColor) and @link(AttributeColorDef). }
397 procedure AttributeColorSet(const AttrName: String; const Value: TCastleColor); overload;
398
399 { Set the attribute as TCastleColorRGB converted to HEX string,
400 such that it's readable back by @link(AttributeColorRGB) and @link(AttributeColorRGBDef). }
401 procedure AttributeColorSet(const AttrName: String; const Value: TCastleColorRGB); overload;
402
403 { Other methods ---------------------------------------------------------- }
404
405 { Get child element with given ChildName.
406
407 For example use @code(LevelElement.Child('items'))
408 to get the <items> element within <level> element, as in example below.
409
410 @preformatted(
411 <level>
412 <creatures>
413 ...
414 </creatures>
415 <items>
416 ...
417 </items>
418 </level>
419 )
420
421 There must be @bold(one and only one child element with this name).
422 In case there's zero, or more than one such element,
423 we will raise EDOMChildElementError (if Required is @true, default)
424 or return @nil (if Required is @false).
425
426 If there are multiple occurences and Required is @false, then
427 we return @nil. If WarnOnMultiple we will also make a warning in this case,
428 since we don't know which to return, but it it probably a mistake in XML file.
429
430 @raises(EDOMChildElementError
431 If child not found (or found more than once), and Required = @true.) }
432 function Child(const ChildName: String;
433 const Required: boolean = true;
434 const WarnOnMultiple: boolean = true): TDOMElement;
435
436 { Same as @link(Child). }
437 function ChildElement(const ChildName: String;
438 const Required: boolean = true;
439 const WarnOnMultiple: boolean = true): TDOMElement;
440
441 { Create a new child element under this element, and return it. }
442 function CreateChild(const ChildName: String): TDOMElement;
443
444 { Iterator over all children elements. Use like this:
445
446 @longCode(#
447 var
448 I: TXMLElementIterator;
449 begin
450 I := Element.ChildrenIterator;
451 try
452 while I.GetNext do
453 begin
454 // ... here goes your code to process I.Current ...
455 end;
456 finally FreeAndNil(I) end;
457 end;
458 #) }
459 function ChildrenIterator: TXMLElementIterator; overload;
460
461 { Iterator over all children elements named ChildName. Use like this:
462
463 @longCode(#
464 var
465 I: TXMLElementIterator;
466 begin
467 I := Element.ChildrenIterator('item');
468 try
469 while I.GetNext do
470 begin
471 // ... here goes your code to process I.Current ...
472 end;
473 finally FreeAndNil(I) end;
474 end;
475 #) }
476 function ChildrenIterator(const ChildName: String): TXMLElementIterator; overload;
477
478 { The text data contained in this element.
479
480 This is suitable if an element is supposed to contain only some text.
481 Like @code(<some_value>This is a text inside.</some_value>).
482 It raises an error if an element contains anything else as child.
483
484 If there are no text data nodes, e.g. if the element is empty,
485 it returns empty string without raising any error. }
486 function TextData: String;
487
488 { Tag name (element name).
489 Expressed as an 8-bit string (in UTF-8 encoding), contrary to the TagName
490 from FPC DOM unit that is a WideString (DOMString). }
491 function TagName8: String;
492 end;
493
494 { Iterate over all children elements of given XML element.
495
496 Without this, typical iteration looks like
497
498 @longCode(#
499 var
500 Index: Integer;
501 ChildrenList: TDOMNodeList;
502 ChildNode: TDOMNode;
503 ChildElement: TDOMElement;
504 begin
505 ChildrenList := Element.ChildNodes;
506
507 for Index := 0 to ChildrenList.Count - 1 do
508 begin
509 ChildNode := ChildrenList.Item[Index];
510 if ChildNode.NodeType = ELEMENT_NODE then
511 begin
512 ChildElement := ChildNode as TDOMElement;
513 ... here goes your code to process ChildElement ...
514 end;
515 end;
516 end;
517 #)
518
519 ... which is an easy code, but it becomes tiresome
520 to write this over and over again, especially
521 for units that heavily process XML (like X3D XML or Collada readers).
522 So this class allows you to write instead
523
524 @longCode(#
525 var
526 I: TXMLElementIterator;
527 begin
528 I := Element.ChildrenIterator;
529 try
530 while I.GetNext do
531 begin
532 ... here goes your code to process I.Current ...
533 end;
534 finally FreeAndNil(I) end;
535 end;
536 #) }
537 TXMLElementIterator = class
538 private
539 ChildNodes: TDOMNodeList;
540 ChildIndex: Integer;
541 FCurrent: TDOMElement;
542 public
543 constructor Create(ParentElement: TDOMElement);
544 function GetNext: boolean; virtual;
545 property Current: TDOMElement read FCurrent;
546 procedure Rewind;
547 function Count: Integer;
548 end;
549
550 { Iterate over children elements of given XML element, that have matching TagName. }
551 TXMLElementFilteringIterator = class(TXMLElementIterator)
552 private
553 FTagName: DOMString;
554 public
555 constructor Create(ParentElement: TDOMElement; const TagName: String);
556 function GetNext: boolean; override;
557 end;
558
559 { Iterate over all CDATA nodes of given XML element.
560
561 Simple usage:
562
563 @longCode(#
564 var
565 I: TXMLCDataIterator;
566 begin
567 I := TXMLCDataIterator.Create(Element);
568 try
569 while I.GetNext do
570 begin
571 ... here goes your code to process I.Current ...
572 end;
573 finally FreeAndNil(I) end;
574 end;
575 #) }
576 TXMLCDataIterator = class
577 private
578 ChildNodes: TDOMNodeList;
579 ChildIndex: Integer;
580 FCurrent: String;
581 public
582 constructor Create(ParentElement: TDOMElement);
583 destructor Destroy; override;
584 function GetNext: boolean;
585 property Current: String read FCurrent;
586 end;
587
588 { Retrieves from Element attribute Value and returns @true,
589 or (if there is no such attribute) returns @false
590 and does not modify Value. Value is a "var", not "out" param,
591 because in the latter case it's guaranteed that the old Value
592 will not be cleared.
593
594 @deprecated Deprecated, use Element.AttributeString instead. }
595 function DOMGetAttribute(const Element: TDOMElement;
596 const AttrName: String; var Value: String): boolean;
597 deprecated 'use helper method AttributeString on TDOMElement';
598
599 { Like DOMGetAttribute, but reads Cardinal value.
600
601 @deprecated Deprecated, use Element.AttributeCardinal instead. }
602 function DOMGetCardinalAttribute(const Element: TDOMElement;
603 const AttrName: String; var Value: Cardinal): boolean;
604 deprecated 'use helper method AttributeCardinal on TDOMElement';
605
606 { Like DOMGetAttribute, but reads Integer value.
607
608 @deprecated Deprecated, use Element.AttributeInteger instead. }
609 function DOMGetIntegerAttribute(const Element: TDOMElement;
610 const AttrName: String; var Value: Integer): boolean;
611 deprecated 'use helper method AttributeInteger on TDOMElement';
612
613 { Like DOMGetAttribute, but reads Single value.
614
615 @deprecated Deprecated, use Element.AttributeSingle instead. }
616 function DOMGetSingleAttribute(const Element: TDOMElement;
617 const AttrName: String; var Value: Single): boolean;
618 deprecated 'use helper method AttributeSingle on TDOMElement';
619
620 { Like DOMGetAttribute, but reads Float value.
621
622 @deprecated Deprecated, use Element.AttributeFloat instead. }
623 function DOMGetFloatAttribute(const Element: TDOMElement;
624 const AttrName: String; var Value: Float): boolean;
625 deprecated 'use helper method AttributeFloat on TDOMElement';
626
627 { Like DOMGetAttribute, but reads Boolean value.
628 A boolean value is interpreted just like FPC's TXMLConfig
629 objects: true is designated by word @code(true), false by word
630 @code(false), case is ignored.
631
632 If attribute exists but it's value
633 is not @code(true) or @code(false), then returns @false and doesn't
634 modify Value paramater. So behaves just like the attribute didn't exist.
635
636 @deprecated Deprecated, use Element.AttributeBoolean instead. }
637 function DOMGetBooleanAttribute(const Element: TDOMElement;
638 const AttrName: String; var Value: boolean): boolean;
639 deprecated 'use helper method AttributeBoolean on TDOMElement';
640
641 function DOMGetTextData(const Element: TDOMElement): String;
642 deprecated 'use TDOMElement helper called TextData';
643
644 { Gets a child of Element named ChildName, and gets text data within
645 this child.
646
647 This is just a shortcut for @code(DOMGetTextData(DOMGetChildElement(Element,
648 ChildName, true))).
649
650 @raises(EDOMChildElementError
651 If child not found or found more than once and RaiseOnError) }
652 function DOMGetTextChild(const Element: TDOMElement;
653 const ChildName: String): String;
654 deprecated 'This method did not prove to be of much use, and it only clutters the API. Don''t use, or show us a convincing usecase when this is sensible.';
655
656 { If needed, free result of TDOMElement.ChildNodes.
657
658 This abstracts FPC DOM unit differences:
659 @unorderedList(
660 @item(
661 For FPC <= 2.2.x, it was needed to call ChildNodes.Release when you're
662 done with them.)
663
664 @item(
665 In newer FPC, you do not have to free nodes at all (since FPC rev 13143),
666 and their Release method doesn't exist (since rev 13113).)
667 ) }
668 procedure FreeChildNodes(const ChildNodes: TDOMNodeList);
669 deprecated 'this is useless since a long time (FPC >= 2.4.x), you can remove this as the engine does not support older FPC versions anyway';
670
671 { Replacements for standard ReadXMLFile and WriteXMLFile that operate on URLs.
672 Optionally they can encrypt / decrypt content using BlowFish.
673 @groupBegin }
674 procedure UrlReadXML(out Doc: TXMLDocument; const Url: String); overload;
675 function UrlReadXML(const Url: String): TXMLDocument; overload;
676 procedure UrlWriteXML(Doc: TXMLDocument; const Url: String); overload;
677
678 {$ifdef FPC}
679 procedure UrlReadXML(out Doc: TXMLDocument; const Url: String; const BlowFishKeyPhrase: String); overload;
680 function UrlReadXML(const Url: String; const BlowFishKeyPhrase: String): TXMLDocument; overload;
681 procedure UrlWriteXML(Doc: TXMLDocument; const Url: String; const BlowFishKeyPhrase: String); overload;
682 {$endif}
683 { @groupEnd }
684
685 implementation
686
687 uses Classes, XMLRead, XMLWrite, {$ifdef FPC} BlowFish, {$endif}
688 CastleUriUtils, CastleClassUtils, CastleInternalFileMonitor, CastleStringUtils,
689 CastleLog;
690
691 { TDOMNodeHelper ------------------------------------------------------------- }
692
693 function TDOMNodeHelper.NodeName8: String;
694 begin
695 Result := UTF8Encode(NodeName);
696 end;
697
698 function TDOMNodeHelper.GetNodeValue8: String;
699 begin
700 Result := UTF8Encode(NodeValue);
701 end;
702
703 procedure TDOMNodeHelper.SetNodeValue8(const S: String);
704 begin
705 NodeValue := UTF8Decode(S);
706 end;
707
708 { TDOMCharacterDataHelper ---------------------------------------------------- }
709
710 function TDOMCharacterDataHelper.Data8: String;
711 begin
712 Result := UTF8Encode(Data);
713 end;
714
715 { ----------------------------------------------------------------------------
716 TDOMElementHelper:
717 Get an optional attribute to a "var" parameter, returns if found. }
718
719 {$ifdef FPC}
720 function TDOMElementHelper.AttributeString(const AttrName: String; var Value: String): boolean;
721 var
722 AttrNode: TDOMNode;
723 begin
724 AttrNode := Attributes.GetNamedItem(UTF8decode(AttrName));
725 Result := AttrNode <> nil;
726 if Result then
727 begin
728 Check(AttrNode.NodeType = ATTRIBUTE_NODE,
729 'All element attributes must have ATTRIBUTE_NODE');
730 Value := UTF8Encode((AttrNode as TDOMAttr).Value);
731 end;
732 end;
733 {$endif}
734
735 function TDOMElementHelper.AttributeUrl(
736 const AttrName: String; const BaseUrl: String; var Url: String): boolean;
737 begin
738 Result := AttributeString(AttrName, Url);
739 if Result then
740 Url := CombineURI(BaseUrl, Url);
741 end;
742
743 function TDOMElementHelper.AttributeCardinal(
744 const AttrName: String; var Value: Cardinal): boolean;
745 var
746 ValueStr: String;
747 begin
748 Result := AttributeString(AttrName, ValueStr);
749 if Result then
750 Value := StrToInt64(ValueStr);
751 end;
752
753 function TDOMElementHelper.AttributeInteger(
754 const AttrName: String; var Value: Integer): boolean;
755 var
756 ValueStr: String;
757 begin
758 Result := AttributeString(AttrName, ValueStr);
759 if Result then
760 Value := StrToInt(ValueStr);
761 end;
762
763 function TDOMElementHelper.AttributeInt64(
764 const AttrName: String; var Value: Int64): boolean;
765 var
766 ValueStr: String;
767 begin
768 Result := AttributeString(AttrName, ValueStr);
769 if Result then
770 Value := StrToInt64(ValueStr);
771 end;
772
773 function TDOMElementHelper.AttributeQWord(
774 const AttrName: String; var Value: QWord): boolean;
775 var
776 ValueStr: String;
777 begin
778 Result := AttributeString(AttrName, ValueStr);
779 if Result then
780 Value := StrToQWord(ValueStr);
781 end;
782
783 function TDOMElementHelper.AttributeSingle(
784 const AttrName: String; var Value: Single): boolean;
785 var
786 ValueStr: String;
787 begin
788 Result := AttributeString(AttrName, ValueStr);
789 if Result then
790 Value := StrToFloatDot(ValueStr);
791 end;
792
793 function TDOMElementHelper.AttributeFloat(
794 const AttrName: String; var Value: Float): boolean;
795 var
796 ValueStr: String;
797 begin
798 Result := AttributeString(AttrName, ValueStr);
799 if Result then
800 Value := StrToFloatDot(ValueStr);
801 end;
802
803 function TDOMElementHelper.AttributeBoolean(
804 const AttrName: String; var Value: boolean): boolean;
805 var
806 ValueStr: String;
807 begin
808 Result := AttributeString(AttrName, ValueStr);
809 if Result then
810 begin
811 if AnsiCompareText(ValueStr, 'TRUE') = 0 then
812 Value := true else
813 if AnsiCompareText(ValueStr, 'FALSE') = 0 then
814 Value := false else
815 Result := false;
816 end;
817 end;
818
819 function TDOMElementHelper.AttributeColor(
820 const AttrName: String; var Value: TCastleColor): Boolean;
821 var
822 ValueStr: String;
823 begin
824 Result := AttributeString(AttrName, ValueStr);
825 if Result then
826 begin
827 if CountTokens(ValueStr) = 4 then
828 Value := Vector4FromStr(ValueStr)
829 else
830 Value := HexToColor(ValueStr);
831 end;
832 end;
833
834 function TDOMElementHelper.AttributeColorRGB(
835 const AttrName: String; var Value: TCastleColorRGB): Boolean;
836 var
837 ValueStr: String;
838 begin
839 Result := AttributeString(AttrName, ValueStr);
840 if Result then
841 begin
842 if CountTokens(ValueStr) = 3 then
843 Value := Vector3FromStr(ValueStr)
844 else
845 Value := HexToColorRGB(ValueStr);
846 end;
847 end;
848
849 function TDOMElementHelper.AttributeVector2(
850 const AttrName: String; var Value: TVector2): boolean;
851 var
852 ValueStr: String;
853 begin
854 Result := AttributeString(AttrName, ValueStr);
855 if Result then
856 Value := Vector2FromStr(ValueStr);
857 end;
858
859 function TDOMElementHelper.AttributeVector3(
860 const AttrName: String; var Value: TVector3): boolean;
861 var
862 ValueStr: String;
863 begin
864 Result := AttributeString(AttrName, ValueStr);
865 if Result then
866 Value := Vector3FromStr(ValueStr);
867 end;
868
869 function TDOMElementHelper.AttributeVector4(
870 const AttrName: String; var Value: TVector4): boolean;
871 var
872 ValueStr: String;
873 begin
874 Result := AttributeString(AttrName, ValueStr);
875 if Result then
876 Value := Vector4FromStr(ValueStr);
877 end;
878
879 { ------------------------------------------------------------------------
880 TDOMElementHelper:
881 Get a required attribute, returns value (exception if not found). }
882
883 function TDOMElementHelper.AttributeString(const AttrName: String): String;
884 begin
885 if not AttributeString(AttrName, Result) then
886 raise EDOMAttributeMissing.CreateFmt('Missing required (string) attribute "%s" on element "%s"', [AttrName, TagName]);
887 end;
888
889 function TDOMElementHelper.AttributeUrl(const AttrName: String; const BaseUrl: String): String;
890 begin
891 if not AttributeUrl(AttrName, BaseUrl, Result) then
892 raise EDOMAttributeMissing.CreateFmt('Missing required (URL) attribute "%s" on element "%s"', [AttrName, TagName]);
893 end;
894
895 function TDOMElementHelper.AttributeCardinal(const AttrName: String): Cardinal;
896 begin
897 if not AttributeCardinal(AttrName, Result) then
898 raise EDOMAttributeMissing.CreateFmt('Missing required (unsigned integer) attribute "%s" on element "%s"', [AttrName, TagName]);
899 end;
900
901 function TDOMElementHelper.AttributeInteger(const AttrName: String): Integer;
902 begin
903 if not AttributeInteger(AttrName, Result) then
904 raise EDOMAttributeMissing.CreateFmt('Missing required (integer) attribute "%s" on element "%s"', [AttrName, TagName]);
905 end;
906
907 function TDOMElementHelper.AttributeInt64(const AttrName: String): Int64;
908 begin
909 if not AttributeInt64(AttrName, Result) then
910 raise EDOMAttributeMissing.CreateFmt('Missing required (64-bit integer) attribute "%s" on element "%s"', [AttrName, TagName]);
911 end;
912
913 function TDOMElementHelper.AttributeQWord(const AttrName: String): QWord;
914 begin
915 if not AttributeQWord(AttrName, Result) then
916 raise EDOMAttributeMissing.CreateFmt('Missing required (unsigned 64-bit integer) attribute "%s" on element "%s"', [AttrName, TagName]);
917 end;
918
919 function TDOMElementHelper.AttributeSingle(const AttrName: String): Single;
920 begin
921 if not AttributeSingle(AttrName, Result) then
922 raise EDOMAttributeMissing.CreateFmt('Missing required (float) attribute "%s" on element "%s"', [AttrName, TagName]);
923 end;
924
925 function TDOMElementHelper.AttributeFloat(const AttrName: String): Float;
926 begin
927 if not AttributeFloat(AttrName, Result) then
928 raise EDOMAttributeMissing.CreateFmt('Missing required (float) attribute "%s" on element "%s"', [AttrName, TagName]);
929 end;
930
931 function TDOMElementHelper.AttributeBoolean(const AttrName: String): boolean;
932 begin
933 if not AttributeBoolean(AttrName, Result) then
934 raise EDOMAttributeMissing.CreateFmt('Missing (or has an invalid value) required (boolean) attribute "%s" on element "%s"', [AttrName, TagName]);
935 end;
936
937 function TDOMElementHelper.AttributeColor(const AttrName: String): TCastleColor;
938 begin
939 if not AttributeColor(AttrName, Result) then
940 raise EDOMAttributeMissing.CreateFmt('Missing (or has an invalid value) required (color) attribute "%s" on element "%s"', [AttrName, TagName]);
941 end;
942
943 function TDOMElementHelper.AttributeColorRGB(const AttrName: String): TCastleColorRGB;
944 begin
945 if not AttributeColorRGB(AttrName, Result) then
946 raise EDOMAttributeMissing.CreateFmt('Missing (or has an invalid value) required (RGB color) attribute "%s" on element "%s"', [AttrName, TagName]);
947 end;
948
949 function TDOMElementHelper.AttributeVector2(const AttrName: String): TVector2;
950 begin
951 if not AttributeVector2(AttrName, Result) then
952 raise EDOMAttributeMissing.CreateFmt('Missing (or has an invalid value) required (vector2) attribute "%s" on element "%s"', [AttrName, TagName]);
953 end;
954
955 function TDOMElementHelper.AttributeVector3(const AttrName: String): TVector3;
956 begin
957 if not AttributeVector3(AttrName, Result) then
958 raise EDOMAttributeMissing.CreateFmt('Missing (or has an invalid value) required (vector3) attribute "%s" on element "%s"', [AttrName, TagName]);
959 end;
960
961 function TDOMElementHelper.AttributeVector4(const AttrName: String): TVector4;
962 begin
963 if not AttributeVector4(AttrName, Result) then
964 raise EDOMAttributeMissing.CreateFmt('Missing (or has an invalid value) required (vector4) attribute "%s" on element "%s"', [AttrName, TagName]);
965 end;
966
967 { ------------------------------------------------------------------------
968 TDOMElementHelper:
969 Get an optional attribute, returns attribute or a default value. }
970
971 function TDOMElementHelper.AttributeStringDef(const AttrName: String; const DefaultValue: String): String;
972 begin
973 if not AttributeString(AttrName, Result) then
974 Result := DefaultValue;
975 end;
976
977 function TDOMElementHelper.AttributeIntegerDef(const AttrName: String; const DefaultValue: Integer): Integer;
978 begin
979 if not AttributeInteger(AttrName, Result) then
980 Result := DefaultValue;
981 end;
982
983 function TDOMElementHelper.AttributeInt64Def(const AttrName: String; const DefaultValue: Int64): Int64;
984 begin
985 if not AttributeInt64(AttrName, Result) then
986 Result := DefaultValue;
987 end;
988
989 function TDOMElementHelper.AttributeQWordDef(const AttrName: String; const DefaultValue: QWord): QWord;
990 begin
991 if not AttributeQWord(AttrName, Result) then
992 Result := DefaultValue;
993 end;
994
995 function TDOMElementHelper.AttributeCardinalDef(const AttrName: String; const DefaultValue: Cardinal): Cardinal;
996 begin
997 if not AttributeCardinal(AttrName, Result) then
998 Result := DefaultValue;
999 end;
1000
1001 function TDOMElementHelper.AttributeSingleDef(const AttrName: String; const DefaultValue: Single): Single;
1002 begin
1003 if not AttributeSingle(AttrName, Result) then
1004 Result := DefaultValue;
1005 end;
1006
1007 function TDOMElementHelper.AttributeFloatDef(const AttrName: String; const DefaultValue: Float): Float;
1008 begin
1009 if not AttributeFloat(AttrName, Result) then
1010 Result := DefaultValue;
1011 end;
1012
1013 function TDOMElementHelper.AttributeBooleanDef(const AttrName: String; const DefaultValue: boolean): boolean;
1014 begin
1015 if not AttributeBoolean(AttrName, Result) then
1016 Result := DefaultValue;
1017 end;
1018
1019 function TDOMElementHelper.AttributeColorDef(const AttrName: String; const DefaultValue: TCastleColor): TCastleColor;
1020 begin
1021 if not AttributeColor(AttrName, Result) then
1022 Result := DefaultValue;
1023 end;
1024
1025 function TDOMElementHelper.AttributeColorRGBDef(const AttrName: String; const DefaultValue: TCastleColorRGB): TCastleColorRGB;
1026 begin
1027 if not AttributeColorRGB(AttrName, Result) then
1028 Result := DefaultValue;
1029 end;
1030
1031 function TDOMElementHelper.AttributeVector2Def(const AttrName: String; const DefaultValue: TVector2): TVector2;
1032 begin
1033 if not AttributeVector2(AttrName, Result) then
1034 Result := DefaultValue;
1035 end;
1036
1037 function TDOMElementHelper.AttributeVector3Def(const AttrName: String; const DefaultValue: TVector3): TVector3;
1038 begin
1039 if not AttributeVector3(AttrName, Result) then
1040 Result := DefaultValue;
1041 end;
1042
1043 function TDOMElementHelper.AttributeVector4Def(const AttrName: String; const DefaultValue: TVector4): TVector4;
1044 begin
1045 if not AttributeVector4(AttrName, Result) then
1046 Result := DefaultValue;
1047 end;
1048
1049 { TDOMElementHelper: Attribute setting ------------------------------------------------------ }
1050
1051 procedure TDOMElementHelper.AttributeSet(const AttrName: String; const Value: String);
1052 begin
1053 SetAttribute(UTF8Decode(AttrName), UTF8Decode(Value));
1054 end;
1055
1056 procedure TDOMElementHelper.AttributeSet(const AttrName: String; const Value: boolean);
1057 begin
1058 SetAttribute(UTF8Decode(AttrName), UTF8Decode(BoolToStr(Value, true)));
1059 end;
1060
1061 procedure TDOMElementHelper.AttributeSet(const AttrName: String; const Value: Integer);
1062 begin
1063 SetAttribute(UTF8Decode(AttrName), UTF8Decode(IntToStr(Value)));
1064 end;
1065
1066 procedure TDOMElementHelper.AttributeSet(const AttrName: String; const Value: Int64);
1067 begin
1068 SetAttribute(UTF8Decode(AttrName), UTF8Decode(IntToStr(Value)));
1069 end;
1070
1071 procedure TDOMElementHelper.AttributeSet(const AttrName: String; const Value: QWord);
1072 begin
1073 SetAttribute(UTF8Decode(AttrName), UTF8Decode(IntToStr(Value)));
1074 end;
1075
1076 procedure TDOMElementHelper.AttributeSet(const AttrName: String; const Value: Cardinal);
1077 begin
1078 SetAttribute(UTF8Decode(AttrName), UTF8Decode(IntToStr(Value)));
1079 end;
1080
1081 procedure TDOMElementHelper.AttributeSet(const AttrName: String; const Value: Single);
1082 begin
1083 SetAttribute(UTF8Decode(AttrName), UTF8Decode(FloatToStrDot(Value)));
1084 end;
1085
1086 procedure TDOMElementHelper.AttributeSet(const AttrName: String; const Value: TVector2);
1087 begin
1088 SetAttribute(UTF8Decode(AttrName), UTF8Decode(Value.ToRawString));
1089 end;
1090
1091 procedure TDOMElementHelper.AttributeSet(const AttrName: String; const Value: TVector3);
1092 begin
1093 SetAttribute(UTF8Decode(AttrName), UTF8Decode(Value.ToRawString));
1094 end;
1095
1096 procedure TDOMElementHelper.AttributeSet(const AttrName: String; const Value: TVector4);
1097 begin
1098 SetAttribute(UTF8Decode(AttrName), UTF8Decode(Value.ToRawString));
1099 end;
1100
1101 procedure TDOMElementHelper.AttributeColorSet(const AttrName: String;
1102 const Value: TCastleColor);
1103 begin
1104 SetAttribute(UTF8Decode(AttrName), UTF8Decode(ColorToHex(Value)));
1105 end;
1106
1107 procedure TDOMElementHelper.AttributeColorSet(const AttrName: String;
1108 const Value: TCastleColorRGB);
1109 begin
1110 SetAttribute(UTF8Decode(AttrName), UTF8Decode(ColorRGBToHex(Value)));
1111 end;
1112
1113 { ------------------------------------------------------------------------
1114 TDOMElementHelper: Other methods. }
1115
1116 function TDOMElementHelper.ChildElement(const ChildName: String;
1117 const Required, WarnOnMultiple: boolean): TDOMElement;
1118 begin
1119 Result := Child(ChildName, Required, WarnOnMultiple);
1120 end;
1121
1122 function TDOMElementHelper.Child(const ChildName: String;
1123 const Required, WarnOnMultiple: boolean): TDOMElement;
1124 var
1125 Children: TDOMNodeList;
1126 Node: TDOMNode;
1127 I: Integer;
1128 begin
1129 Result := nil;
1130 Children := ChildNodes;
1131
1132 for I := 0 to Integer(Children.Count) - 1 do
1133 begin
1134 Node := Children.Item[I];
1135 if (Node.NodeType = ELEMENT_NODE) and
1136 ((Node as TDOMElement).TagName = UTF8Decode(ChildName)) then
1137 begin
1138 if Result = nil then
1139 Result := TDOMElement(Node) else
1140 begin
1141 if Required then
1142 begin
1143 raise EDOMChildElementError.CreateFmt(
1144 'Child "%s" occurs more than once', [ChildName]);
1145 end else
1146 begin
1147 if WarnOnMultiple then
1148 WritelnWarning('XML', Format('Child "%s" occurs more than once, ignoring all occurences', [ChildName]));
1149 Exit(nil);
1150 end;
1151 end;
1152 end;
1153 end;
1154
1155 if (Result = nil) and Required then
1156 raise EDOMChildElementError.CreateFmt('Child "%s" not found', [ChildName])
1157 end;
1158
1159 function TDOMElementHelper.TextData: String;
1160
1161 {
1162 It concatenates all text data nodes that are direct children
1163 of this element. So if there are no text data nodes, it returns
1164 empty string without raising any error.
1165
1166 AFAIK it's uncommon but
1167 possible to have here more than one text node. Normally, more than one
1168 text nodes occur because they are separated by other child elements,
1169 but we already eliminated this possibility (i.e. we raise error
1170 in this case). Still, if you operated on DOM tree, e.g. deleted
1171 some elements, or inserted some text nodes, then I think it's possible
1172 that you will have more than one text node within this element.
1173 So this procedure should still work OK in this case.
1174 }
1175
1176 var
1177 Children: TDOMNodeList;
1178 Node: TDOMNode;
1179 I: Integer;
1180 begin
1181 Result := '';
1182 Children := ChildNodes;
1183 for I := 0 to Integer(Children.Count) - 1 do
1184 begin
1185 Node := Children.Item[I];
1186 case Node.NodeType of
1187 TEXT_NODE: Result := Result + (Node as TDOMText).NodeValue8;
1188 ELEMENT_NODE: raise Exception.CreateFmt(
1189 'Child elements not allowed within element <%s>, but found %s',
1190 [TagName, (Node as TDOMElement).TagName]);
1191 end;
1192 end;
1193 end;
1194
1195 function TDOMElementHelper.CreateChild(const ChildName: String): TDOMElement;
1196 begin
1197 Result := OwnerDocument.CreateElement(UTF8Decode(ChildName));
1198 AppendChild(Result);
1199 end;
1200
1201 function TDOMElementHelper.ChildrenIterator: TXMLElementIterator;
1202 begin
1203 Result := TXMLElementIterator.Create(Self);
1204 end;
1205
1206 function TDOMElementHelper.ChildrenIterator(const ChildName: String): TXMLElementIterator;
1207 begin
1208 Result := TXMLElementFilteringIterator.Create(Self, ChildName);
1209 end;
1210
1211 function TDOMElementHelper.TagName8: String;
1212 begin
1213 Result := UTF8Encode(TagName);
1214 end;
1215
1216 { TXMLElementIterator -------------------------------------------------------- }
1217
1218 constructor TXMLElementIterator.Create(ParentElement: TDOMElement);
1219 begin
1220 inherited Create;
1221 ChildNodes := ParentElement.ChildNodes;
1222 ChildIndex := -1;
1223 end;
1224
1225 procedure TXMLElementIterator.Rewind;
1226 begin
1227 ChildIndex := -1;
1228 end;
1229
1230 function TXMLElementIterator.Count: Integer;
1231 begin
1232 Result := ChildNodes.Count;
1233 end;
1234
1235 function TXMLElementIterator.GetNext: boolean;
1236 var
1237 ChildNode: TDOMNode;
1238 begin
1239 repeat
1240 Inc(ChildIndex);
1241
1242 if ChildIndex >= Integer(ChildNodes.Count) then
1243 begin
1244 Result := false;
1245 Break;
1246 end else
1247 begin
1248 ChildNode := ChildNodes[ChildIndex];
1249 if ChildNode.NodeType = ELEMENT_NODE then
1250 begin
1251 Result := true;
1252 FCurrent := ChildNode as TDOMElement;
1253 Break;
1254 end;
1255 end;
1256 until false;
1257 end;
1258
1259 { TXMLElementFilteringIterator ----------------------------------------------- }
1260
1261 constructor TXMLElementFilteringIterator.Create(ParentElement: TDOMElement; const TagName: String);
1262 begin
1263 inherited Create(ParentElement);
1264 FTagName := UTF8Decode(TagName);
1265 end;
1266
1267 function TXMLElementFilteringIterator.GetNext: boolean;
1268 begin
1269 repeat
1270 Result := inherited GetNext;
1271 until (not Result) or (Current.TagName = FTagName);
1272 end;
1273
1274 { TXMLCDataIterator -------------------------------------------------------- }
1275
1276 constructor TXMLCDataIterator.Create(ParentElement: TDOMElement);
1277 begin
1278 inherited Create;
1279 ChildNodes := ParentElement.ChildNodes;
1280 ChildIndex := -1;
1281 end;
1282
1283 destructor TXMLCDataIterator.Destroy;
1284 begin
1285 inherited;
1286 end;
1287
1288 function TXMLCDataIterator.GetNext: boolean;
1289 var
1290 ChildNode: TDOMNode;
1291 begin
1292 repeat
1293 Inc(ChildIndex);
1294
1295 if ChildIndex >= Integer(ChildNodes.Count) then
1296 begin
1297 Result := false;
1298 Break;
1299 end else
1300 begin
1301 ChildNode := ChildNodes[ChildIndex];
1302 if ChildNode.NodeType = CDATA_SECTION_NODE then
1303 begin
1304 Result := true;
1305 FCurrent := UTF8Encode((ChildNode as TDOMCDataSection).Data);
1306 Break;
1307 end;
1308 end;
1309 until false;
1310 end;
1311
1312 { globals -------------------------------------------------------------------- }
1313
1314 function DOMGetAttribute(const Element: TDOMElement;
1315 const AttrName: String; var Value: String): boolean;
1316 begin
1317 Result := Element.AttributeString(AttrName, Value);
1318 end;
1319
1320 function DOMGetCardinalAttribute(const Element: TDOMElement;
1321 const AttrName: String; var Value: Cardinal): boolean;
1322 begin
1323 Result := Element.AttributeCardinal(AttrName, Value);
1324 end;
1325
1326 function DOMGetIntegerAttribute(const Element: TDOMElement;
1327 const AttrName: String; var Value: Integer): boolean;
1328 begin
1329 Result := Element.AttributeInteger(AttrName, Value);
1330 end;
1331
1332 function DOMGetSingleAttribute(const Element: TDOMElement;
1333 const AttrName: String; var Value: Single): boolean;
1334 begin
1335 Result := Element.AttributeSingle(AttrName, Value);
1336 end;
1337
1338 function DOMGetFloatAttribute(const Element: TDOMElement;
1339 const AttrName: String; var Value: Float): boolean;
1340 begin
1341 Result := Element.AttributeFloat(AttrName, Value);
1342 end;
1343
1344 function DOMGetBooleanAttribute(const Element: TDOMElement;
1345 const AttrName: String; var Value: boolean): boolean;
1346 begin
1347 Result := Element.AttributeBoolean(AttrName, Value);
1348 end;
1349
1350 function DOMGetTextData(const Element: TDOMElement): String;
1351 begin
1352 Result := Element.TextData;
1353 end;
1354
1355 function DOMGetTextChild(const Element: TDOMElement;
1356 const ChildName: String): String;
1357 begin
1358 Result := Element.ChildElement(ChildName).TextData;
1359 end;
1360
1361 procedure FreeChildNodes(const ChildNodes: TDOMNodeList);
1362 begin
1363 {$ifdef VER2_0} ChildNodes.Release; {$endif}
1364 {$ifdef VER2_1} ChildNodes.Release; {$endif}
1365 {$ifdef VER2_2} ChildNodes.Release; {$endif}
1366 end;
1367
1368 {$ifdef FPC}
1369
1370 procedure UrlReadXML(out Doc: TXMLDocument; const Url: String; const BlowFishKeyPhrase: String);
1371 var
1372 Stream: TStream;
1373 DecryptStream: TBlowFishDecryptStream;
1374 DecryptedCorrectStream: TStringStream;
1375 L: Integer;
1376 DecryptedContent: String;
1377 begin
1378 Doc := nil; // clean "out" param at start, just like ReadXMLFile
1379 Stream := Download(Url, []);
1380 try
1381 DecryptStream := TBlowFishDecryptStream.Create(BlowFishKeyPhrase, Stream);
1382 try
1383 { TBlowFishDecryptStream (or maybe encryption?) adds zeros at the end.
1384 Cut them off. }
1385 DecryptedContent := ReadGrowingStreamToString(DecryptStream);
1386 L := Length(DecryptedContent);
1387 while (L > 0) and (DecryptedContent[L] = #0) do
1388 Dec(L);
1389 SetLength(DecryptedContent, L);
1390 DecryptedCorrectStream := TStringStream.Create(DecryptedContent);
1391 try
1392 try
1393 ReadXMLFile(Doc, DecryptedCorrectStream);
1394 except
1395 // on EXMLReadError, improve exception message and reraise
1396 on E: EXMLReadError do
1397 begin
1398 E.Message := E.Message + ' (in file "' + UriDisplay(Url) + '", encrypted)';
1399 raise;
1400 end;
1401 end;
1402 finally FreeAndNil(DecryptedCorrectStream) end;
1403 finally FreeAndNil(DecryptStream) end;
1404 finally FreeAndNil(Stream) end;
1405 end;
1406
1407 {$endif}
1408
1409 procedure UrlReadXML(out Doc: TXMLDocument; const Url: String);
1410 var
1411 Stream: TStream;
1412 StreamOptions: TStreamOptions;
1413 Gzipped: boolean;
1414 begin
1415 Doc := nil; // clean "out" param at start, just like ReadXMLFile
1416
1417 //guess gzipped based on file extension
1418 StreamOptions := [];
1419 UriMimeType(Url, Gzipped);
1420 if Gzipped then
1421 Include(StreamOptions, soGzip);
1422
1423 Stream := Download(Url, StreamOptions);
1424 try
1425 try
1426 ReadXMLFile(Doc, Stream);
1427 except
1428 // on EXMLReadError, improve exception message and reraise
1429 on E: EXMLReadError do
1430 begin
1431 E.Message := E.Message + ' (in file "' + UriDisplay(Url) + '")';
1432 raise;
1433 end;
1434 end;
1435 finally FreeAndNil(Stream) end;
1436 end;
1437
1438 function UrlReadXML(const Url: String): TXMLDocument;
1439 begin
1440 try
1441 // UrlReadXML and ReadXMLFile nil the parameter when there's no need to free it
1442 UrlReadXML(Result, Url); //this one will automatically take care of gzipping
1443 except FreeAndNil(Result); raise; end;
1444 end;
1445
1446 {$ifdef FPC}
1447
1448 function UrlReadXML(const Url: String; const BlowFishKeyPhrase: String): TXMLDocument;
1449 begin
1450 try
1451 // UrlReadXML and ReadXMLFile nil the parameter when there's no need to free it
1452 UrlReadXML(Result, Url, BlowFishKeyPhrase);
1453 except FreeAndNil(Result); raise; end;
1454 end;
1455
1456 procedure UrlWriteXML(Doc: TXMLDocument; const Url: String; const BlowFishKeyPhrase: String);
1457 var
1458 Stream: TStream;
1459 EncryptStream: TBlowFishEncryptStream;
1460 begin
1461 Stream := UrlSaveStream(Url);
1462 try
1463 EncryptStream := TBlowFishEncryptStream.Create(BlowFishKeyPhrase, Stream);
1464 try
1465 WriteXMLFile(Doc, EncryptStream);
1466 finally FreeAndNil(EncryptStream) end;
1467 finally FreeAndNil(Stream) end;
1468 end;
1469
1470 {$endif}
1471
1472 procedure UrlWriteXML(Doc: TXMLDocument; const Url: String);
1473 var
1474 Stream: TStream;
1475 StreamOptions: TSaveStreamOptions;
1476 gzipped: boolean;
1477 begin
1478 //guess gzipped based on file extension
1479 StreamOptions := [];
1480 UriMimeType(Url, Gzipped);
1481 if Gzipped then
1482 Include(StreamOptions, ssoGzip);
1483
1484 Stream := UrlSaveStream(Url, StreamOptions);
1485 try
1486 WriteXMLFile(Doc, Stream);
1487 finally FreeAndNil(Stream) end;
1488
1489 { Caused e.g. by saving sprite sheet file using CGE editor,
1490 calling FileMonitor to refresh scenes using it. }
1491 FileMonitor.Changed(Url);
1492 end;
1493
1494 end.