/
PhobosXml.d
3020 lines (2732 loc) · 82.2 KB
/
PhobosXml.d
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
// Written in the D programming language.
/**
Classes and functions for creating and parsing XML
The basic architecture of this module is that there are standalone functions,
classes for constructing an XML document from scratch (Tag, Element and
Document), and also classes for parsing a pre-existing XML file (ElementParser
and DocumentParser). The parsing classes <i>may</i> be used to build a
Document, but that is not their primary purpose. The handling capabilities of
DocumentParser and ElementParser are sufficiently customizable that you can
make them do pretty much whatever you want.
Example: This example creates a DOM (Document Object Model) tree
from an XML file.
------------------------------------------------------------------------------
import std.xml;
import std.stdio;
import std.string;
// books.xml is used in various samples throughout the Microsoft XML Core
// Services (MSXML) SDK.
//
// See http://msdn2.microsoft.com/en-us/library/ms762271(VS.85).aspx
void main()
{
string s = cast(string)std.file.read("books.xml");
// Check for well-formedness
check(s);
// Make a DOM tree
auto doc = new Document(s);
// Plain-print it
writefln(doc);
}
------------------------------------------------------------------------------
Example: This example does much the same thing, except that the file is
deconstructed and reconstructed by hand. This is more work, but the
techniques involved offer vastly more power.
------------------------------------------------------------------------------
import std.xml;
import std.stdio;
import std.string;
struct Book
{
string id;
string author;
string title;
string genre;
string price;
string pubDate;
string description;
}
void main()
{
string s = cast(string)std.file.read("books.xml");
// Check for well-formedness
check(s);
// Take it apart
Book[] books;
auto xml = new DocumentParser(s);
xml.onStartTag["book"] = (ElementParser xml)
{
Book book;
book.id = xml.tag.attr["id"];
xml.onEndTag["author"] = (in Element e) { book.author = e.text; };
xml.onEndTag["title"] = (in Element e) { book.title = e.text; };
xml.onEndTag["genre"] = (in Element e) { book.genre = e.text; };
xml.onEndTag["price"] = (in Element e) { book.price = e.text; };
xml.onEndTag["publish-date"] = (in Element e) { book.pubDate = e.text; };
xml.onEndTag["description"] = (in Element e) { book.description = e.text; };
xml.parse();
books ~= book;
};
xml.parse();
// Put it back together again;
auto doc = new Document(new Tag("catalog"));
foreach(book;books)
{
auto element = new Element("book");
element.tag.attr["id"] = book.id;
element ~= new Element("author", book.author);
element ~= new Element("title", book.title);
element ~= new Element("genre", book.genre);
element ~= new Element("price", book.price);
element ~= new Element("publish-date",book.pubDate);
element ~= new Element("description", book.description);
doc ~= element;
}
// Pretty-print it
writefln(join(doc.pretty(3),"\n"));
}
-------------------------------------------------------------------------------
Macros:
WIKI=Phobos/StdXml
Copyright: Copyright Janice Caron 2008 - 2009.
License: <a href="http://www.boost.org/LICENSE_1_0.txt">Boost License 1.0</a>.
Authors: Janice Caron
Copyright Janice Caron 2008 - 2009.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
module orange.xml.PhobosXml;
import std.array;
import std.string;
import std.encoding;
import std.ascii;
import std.algorithm : count;
enum cdata = "<![CDATA[";
final class Attribute : Element
{
private alias string tstring;
private tstring name_;
private tstring value_;
this (tstring name, tstring value, Element parent)
{
super(name);
name_ = name;
value_ = value;
parent_ = parent;
}
override tstring name ()
{
return name_;
}
override tstring value ()
{
return value_;
}
}
/**
* Returns true if the character is a character according to the XML standard
*
* Standards: $(LINK2 http://www.w3.org/TR/1998/REC-xml-19980210, XML 1.0)
*
* Params:
* c = the character to be tested
*/
bool isChar(dchar c) // rule 2
{
if (c <= 0xD7FF)
{
if (c >= 0x20)
return true;
switch(c)
{
case 0xA:
case 0x9:
case 0xD:
return true;
default:
return false;
}
}
else if (0xE000 <= c && c <= 0x10FFFF)
{
if ((c & 0x1FFFFE) != 0xFFFE) // U+FFFE and U+FFFF
return true;
}
return false;
}
unittest
{
// const CharTable=[0x9,0x9,0xA,0xA,0xD,0xD,0x20,0xD7FF,0xE000,0xFFFD,
// 0x10000,0x10FFFF];
assert(!isChar(cast(dchar)0x8));
assert( isChar(cast(dchar)0x9));
assert( isChar(cast(dchar)0xA));
assert(!isChar(cast(dchar)0xB));
assert(!isChar(cast(dchar)0xC));
assert( isChar(cast(dchar)0xD));
assert(!isChar(cast(dchar)0xE));
assert(!isChar(cast(dchar)0x1F));
assert( isChar(cast(dchar)0x20));
assert( isChar('J'));
assert( isChar(cast(dchar)0xD7FF));
assert(!isChar(cast(dchar)0xD800));
assert(!isChar(cast(dchar)0xDFFF));
assert( isChar(cast(dchar)0xE000));
assert( isChar(cast(dchar)0xFFFD));
assert(!isChar(cast(dchar)0xFFFE));
assert(!isChar(cast(dchar)0xFFFF));
assert( isChar(cast(dchar)0x10000));
assert( isChar(cast(dchar)0x10FFFF));
assert(!isChar(cast(dchar)0x110000));
debug (stdxml_TestHardcodedChecks)
{
foreach (c; 0 .. dchar.max + 1)
assert(isChar(c) == lookup(CharTable, c));
}
}
/**
* Returns true if the character is whitespace according to the XML standard
*
* Only the following characters are considered whitespace in XML - space, tab,
* carriage return and linefeed
*
* Standards: $(LINK2 http://www.w3.org/TR/1998/REC-xml-19980210, XML 1.0)
*
* Params:
* c = the character to be tested
*/
bool isSpace(dchar c)
{
return c == '\u0020' || c == '\u0009' || c == '\u000A' || c == '\u000D';
}
/**
* Returns true if the character is a digit according to the XML standard
*
* Standards: $(LINK2 http://www.w3.org/TR/1998/REC-xml-19980210, XML 1.0)
*
* Params:
* c = the character to be tested
*/
bool isDigit(dchar c)
{
if (c <= 0x0039 && c >= 0x0030)
return true;
else
return lookup(DigitTable,c);
}
unittest
{
debug (stdxml_TestHardcodedChecks)
{
foreach (c; 0 .. dchar.max + 1)
assert(isDigit(c) == lookup(DigitTable, c));
}
}
/**
* Returns true if the character is a letter according to the XML standard
*
* Standards: $(LINK2 http://www.w3.org/TR/1998/REC-xml-19980210, XML 1.0)
*
* Params:
* c = the character to be tested
*/
bool isLetter(dchar c) // rule 84
{
return isIdeographic(c) || isBaseChar(c);
}
/**
* Returns true if the character is an ideographic character according to the
* XML standard
*
* Standards: $(LINK2 http://www.w3.org/TR/1998/REC-xml-19980210, XML 1.0)
*
* Params:
* c = the character to be tested
*/
bool isIdeographic(dchar c)
{
if (c == 0x3007)
return true;
if (c <= 0x3029 && c >= 0x3021 )
return true;
if (c <= 0x9FA5 && c >= 0x4E00)
return true;
return false;
}
unittest
{
assert(isIdeographic('\u4E00'));
assert(isIdeographic('\u9FA5'));
assert(isIdeographic('\u3007'));
assert(isIdeographic('\u3021'));
assert(isIdeographic('\u3029'));
debug (stdxml_TestHardcodedChecks)
{
foreach (c; 0 .. dchar.max + 1)
assert(isIdeographic(c) == lookup(IdeographicTable, c));
}
}
/**
* Returns true if the character is a base character according to the XML
* standard
*
* Standards: $(LINK2 http://www.w3.org/TR/1998/REC-xml-19980210, XML 1.0)
*
* Params:
* c = the character to be tested
*/
bool isBaseChar(dchar c)
{
return lookup(BaseCharTable,c);
}
/**
* Returns true if the character is a combining character according to the
* XML standard
*
* Standards: $(LINK2 http://www.w3.org/TR/1998/REC-xml-19980210, XML 1.0)
*
* Params:
* c = the character to be tested
*/
bool isCombiningChar(dchar c)
{
return lookup(CombiningCharTable,c);
}
/**
* Returns true if the character is an extender according to the XML standard
*
* Standards: $(LINK2 http://www.w3.org/TR/1998/REC-xml-19980210, XML 1.0)
*
* Params:
* c = the character to be tested
*/
bool isExtender(dchar c)
{
return lookup(ExtenderTable,c);
}
/**
* Encodes a string by replacing all characters which need to be escaped with
* appropriate predefined XML entities.
*
* encode() escapes certain characters (ampersand, quote, apostrophe, less-than
* and greater-than), and similarly, decode() unescapes them. These functions
* are provided for convenience only. You do not need to use them when using
* the std.xml classes, because then all the encoding and decoding will be done
* for you automatically.
*
* If the string is not modified, the original will be returned.
*
* Standards: $(LINK2 http://www.w3.org/TR/1998/REC-xml-19980210, XML 1.0)
*
* Params:
* s = The string to be encoded
*
* Returns: The encoded string
*
* Examples:
* --------------
* writefln(encode("a > b")); // writes "a > b"
* --------------
*/
S encode(S)(S s, S buffer = null)
{
string r;
size_t lastI;
auto result = appender!S();
foreach (i, c; s)
{
switch (c)
{
case '&': r = "&"; break;
case '"': r = """; break;
case '\'': r = "'"; break;
case '<': r = "<"; break;
case '>': r = ">"; break;
default: continue;
}
// Replace with r
result.put(s[lastI .. i]);
result.put(r);
lastI = i + 1;
}
if (!result.data) return s;
result.put(s[lastI .. $]);
return result.data;
}
unittest
{
assert(encode("hello") is "hello");
assert(encode("a > b") == "a > b", encode("a > b"));
assert(encode("a < b") == "a < b");
assert(encode("don't") == "don't");
assert(encode("\"hi\"") == ""hi"", encode("\"hi\""));
assert(encode("cat & dog") == "cat & dog");
}
/**
* Mode to use for decoding.
*
* $(DDOC_ENUM_MEMBERS NONE) Do not decode
* $(DDOC_ENUM_MEMBERS LOOSE) Decode, but ignore errors
* $(DDOC_ENUM_MEMBERS STRICT) Decode, and throw exception on error
*/
enum DecodeMode
{
NONE, LOOSE, STRICT
}
/**
* Decodes a string by unescaping all predefined XML entities.
*
* encode() escapes certain characters (ampersand, quote, apostrophe, less-than
* and greater-than), and similarly, decode() unescapes them. These functions
* are provided for convenience only. You do not need to use them when using
* the std.xml classes, because then all the encoding and decoding will be done
* for you automatically.
*
* This function decodes the entities &amp;, &quot;, &apos;,
* &lt; and &gt,
* as well as decimal and hexadecimal entities such as &#x20AC;
*
* If the string does not contain an ampersand, the original will be returned.
*
* Note that the "mode" parameter can be one of DecodeMode.NONE (do not
* decode), DecodeMode.LOOSE (decode, but ignore errors), or DecodeMode.STRICT
* (decode, and throw a DecodeException in the event of an error).
*
* Standards: $(LINK2 http://www.w3.org/TR/1998/REC-xml-19980210, XML 1.0)
*
* Params:
* s = The string to be decoded
* mode = (optional) Mode to use for decoding. (Defaults to LOOSE).
*
* Throws: DecodeException if mode == DecodeMode.STRICT and decode fails
*
* Returns: The decoded string
*
* Examples:
* --------------
* writefln(decode("a > b")); // writes "a > b"
* --------------
*/
string decode(string s, DecodeMode mode=DecodeMode.LOOSE)
{
if (mode == DecodeMode.NONE) return s;
char[] buffer;
for (size_t i=0; i<s.length; ++i)
{
char c = s[i];
if (c != '&')
{
if (buffer.length != 0) buffer ~= c;
}
else
{
if (buffer.length == 0)
{
buffer = s[0 .. i].dup;
}
if (startsWith(s[i..$],"&#"))
{
try
{
dchar d;
string t = s[i..$];
checkCharRef(t, d);
char[4] temp;
buffer ~= temp[0 .. std.utf.encode(temp, d)];
i = s.length - t.length - 1;
}
catch(Err e)
{
if (mode == DecodeMode.STRICT)
throw new DecodeException("Unescaped &");
buffer ~= '&';
}
}
else if (startsWith(s[i..$],"&" )) { buffer ~= '&'; i += 4; }
else if (startsWith(s[i..$],""")) { buffer ~= '"'; i += 5; }
else if (startsWith(s[i..$],"'")) { buffer ~= '\''; i += 5; }
else if (startsWith(s[i..$],"<" )) { buffer ~= '<'; i += 3; }
else if (startsWith(s[i..$],">" )) { buffer ~= '>'; i += 3; }
else
{
if (mode == DecodeMode.STRICT)
throw new DecodeException("Unescaped &");
buffer ~= '&';
}
}
}
return (buffer.length == 0) ? s : cast(string)buffer;
}
unittest
{
void assertNot(string s)
{
bool b = false;
try { decode(s,DecodeMode.STRICT); }
catch (DecodeException e) { b = true; }
assert(b,s);
}
// Assert that things that should work, do
assert(decode("hello", DecodeMode.STRICT) is "hello");
assert(decode("a > b", DecodeMode.STRICT) == "a > b");
assert(decode("a < b", DecodeMode.STRICT) == "a < b");
assert(decode("don't", DecodeMode.STRICT) == "don't");
assert(decode(""hi"", DecodeMode.STRICT) == "\"hi\"");
assert(decode("cat & dog", DecodeMode.STRICT) == "cat & dog");
assert(decode("*", DecodeMode.STRICT) == "*");
assert(decode("*", DecodeMode.STRICT) == "*");
assert(decode("cat & dog", DecodeMode.LOOSE) == "cat & dog");
assert(decode("a > b", DecodeMode.LOOSE) == "a > b");
assert(decode("&#;", DecodeMode.LOOSE) == "&#;");
assert(decode("&#x;", DecodeMode.LOOSE) == "&#x;");
assert(decode("G;", DecodeMode.LOOSE) == "G;");
assert(decode("G;", DecodeMode.LOOSE) == "G;");
// Assert that things that shouldn't work, don't
assertNot("cat & dog");
assertNot("a > b");
assertNot("&#;");
assertNot("&#x;");
assertNot("G;");
assertNot("G;");
}
/**
* Class representing an XML document.
*
* Standards: $(LINK2 http://www.w3.org/TR/1998/REC-xml-19980210, XML 1.0)
*
*/
class Document : Element
{
/**
* Contains all text which occurs before the root element.
* Defaults to <?xml version="1.0"?>
*/
string prolog = "<?xml version=\"1.0\"?>";
/**
* Contains all text which occurs after the root element.
* Defaults to the empty string
*/
string epilog;
/**
* Constructs a Document by parsing XML text.
*
* This function creates a complete DOM (Document Object Model) tree.
*
* The input to this function MUST be valid XML.
* This is enforced by DocumentParser's in contract.
*
* Params:
* s = the complete XML text.
*/
this(string s)
in
{
assert(s.length != 0);
}
body
{
auto xml = new DocumentParser(s);
string tagString = xml.tag.tagString;
this(xml.tag);
prolog = s[0 .. tagString.ptr - s.ptr];
parse(xml);
epilog = *xml.s;
}
/**
* Constructs a Document from a Tag.
*
* Params:
* tag = the start tag of the document.
*/
this(const(Tag) tag)
{
super(tag);
}
/**
* Compares two Documents for equality
*
* Examples:
* --------------
* Document d1,d2;
* if (d1 == d2) { }
* --------------
*/
override bool opEquals(Object o)
{
const doc = toType!(const Document)(o);
return
(prolog != doc.prolog ) ? false : (
(super != cast(const Element)doc) ? false : (
(epilog != doc.epilog ) ? false : (
true )));
}
/**
* Compares two Documents
*
* You should rarely need to call this function. It exists so that
* Documents can be used as associative array keys.
*
* Examples:
* --------------
* Document d1,d2;
* if (d1 < d2) { }
* --------------
*/
override int opCmp(Object o)
{
const doc = toType!(const Document)(o);
return
((prolog != doc.prolog )
? ( prolog < doc.prolog ? -1 : 1 ) :
((super != cast(const Element)doc)
? ( cast()super < cast()cast(const Element)doc ? -1 : 1 ) :
((epilog != doc.epilog )
? ( epilog < doc.epilog ? -1 : 1 ) :
0 )));
}
/**
* Returns the hash of a Document
*
* You should rarely need to call this function. It exists so that
* Documents can be used as associative array keys.
*/
override hash_t toHash() @trusted
{
return hash(prolog, hash(epilog, (cast()super).toHash()));
}
/**
* Returns the string representation of a Document. (That is, the
* complete XML of a document).
*/
override string toString() const
{
return prolog ~ super.toString ~ epilog;
}
}
/**
* Class representing an XML element.
*
* Standards: $(LINK2 http://www.w3.org/TR/1998/REC-xml-19980210, XML 1.0)
*/
class Element : Item
{
Tag tag; /// The start tag of the element
Item[] items; /// The element's items
Text[] texts; /// The element's text items
CData[] cdatas; /// The element's CData items
Comment[] comments; /// The element's comments
ProcessingInstruction[] pis; /// The element's processing instructions
Element[] elements; /// The element's child elements
Element parent_;
/**
* Constructs an Element given a name and a string to be used as a Text
* interior.
*
* Params:
* name = the name of the element.
* interior = (optional) the string interior.
*
* Examples:
* -------------------------------------------------------
* auto element = new Element("title","Serenity")
* // constructs the element <title>Serenity</title>
* -------------------------------------------------------
*/
this(string name, string interior=null)
{
this(new Tag(name));
if (interior.length != 0) opCatAssign(new Text(interior));
}
/**
* Constructs an Element from a Tag.
*
* Params:
* tag = the start or empty tag of the element.
*/
this(const(Tag) tag_)
{
this.tag = new Tag(tag_.name);
tag.type = TagType.EMPTY;
foreach(k,v;tag_.attr) tag.attr[k] = v;
tag.tagString = tag_.tagString;
}
Element parent ()
{
return parent_;
}
Element parent (Element parent)
{
return parent_ = parent;
}
string name ()
{
return tag.name;
}
string value ()
{
return text;
}
alias elements children;
Attribute[] attributes ()
{
auto attrs = new Attribute[tag.attr.length];
attrs = attrs[0 .. 0];
foreach (k, v ; tag.attr)
attrs ~= new Attribute(k, v, this);
return attrs;
}
Element query ()
{
return this;
}
Element attribute (string prefix, string name, string value = null)
{
tag.attr[name] = value;
return this;
}
/**
* Append a text item to the interior of this element
*
* Params:
* item = the item you wish to append.
*
* Examples:
* --------------
* Element element;
* element ~= new Text("hello");
* --------------
*/
void opCatAssign(Text item)
{
texts ~= item;
appendItem(item);
}
/**
* Append a CData item to the interior of this element
*
* Params:
* item = the item you wish to append.
*
* Examples:
* --------------
* Element element;
* element ~= new CData("hello");
* --------------
*/
void opCatAssign(CData item)
{
cdatas ~= item;
appendItem(item);
}
/**
* Append a comment to the interior of this element
*
* Params:
* item = the item you wish to append.
*
* Examples:
* --------------
* Element element;
* element ~= new Comment("hello");
* --------------
*/
void opCatAssign(Comment item)
{
comments ~= item;
appendItem(item);
}
/**
* Append a processing instruction to the interior of this element
*
* Params:
* item = the item you wish to append.
*
* Examples:
* --------------
* Element element;
* element ~= new ProcessingInstruction("hello");
* --------------
*/
void opCatAssign(ProcessingInstruction item)
{
pis ~= item;
appendItem(item);
}
/**
* Append a complete element to the interior of this element
*
* Params:
* item = the item you wish to append.
*
* Examples:
* --------------
* Element element;
* Element other = new Element("br");
* element ~= other;
* // appends element representing <br />
* --------------
*/
void opCatAssign(Element item)
{
elements ~= item;
appendItem(item);
}
private void appendItem(Item item)
{
items ~= item;
if (tag.type == TagType.EMPTY && !item.isEmptyXML)
tag.type = TagType.START;
}
private void parse(ElementParser xml)
{
xml.onText = (string s) { opCatAssign(new Text(s)); };
xml.onCData = (string s) { opCatAssign(new CData(s)); };
xml.onComment = (string s) { opCatAssign(new Comment(s)); };
xml.onPI = (string s) { opCatAssign(new ProcessingInstruction(s)); };
xml.onStartTag[null] = (ElementParser xml)
{
auto e = new Element(xml.tag);
e.parse(xml);
opCatAssign(e);
};
xml.parse();
}
/**
* Compares two Elements for equality
*
* Examples:
* --------------
* Element e1,e2;
* if (e1 == e2) { }
* --------------
*/
override bool opEquals(Object o)
{
const element = toType!(const Element)(o);
size_t len = items.length;
if (len != element.items.length) return false;
for (uint i=0; i<len; ++i)
{
if (!items[i].opEquals(cast()element.items[i])) return false;
}
return true;
}
/**
* Compares two Elements
*
* You should rarely need to call this function. It exists so that Elements
* can be used as associative array keys.
*
* Examples:
* --------------
* Element e1,e2;
* if (e1 < e2) { }
* --------------
*/
override int opCmp(Object o)
{
const element = toType!(const Element)(o);
for (uint i=0; ; ++i)
{
if (i == items.length && i == element.items.length) return 0;
if (i == items.length) return -1;
if (i == element.items.length) return 1;
if (items[i] != element.items[i])
return items[i].opCmp(cast()element.items[i]);
}
}
/**
* Returns the hash of an Element
*
* You should rarely need to call this function. It exists so that Elements
* can be used as associative array keys.
*/
override hash_t toHash()
{
hash_t hash = tag.toHash;
foreach(item;items) hash += item.toHash();
return hash;
}
const
{
/**
* Returns the decoded interior of an element.
*
* The element is assumed to containt text <i>only</i>. So, for
* example, given XML such as "<title>Good &amp;
* Bad</title>", will return "Good & Bad".
*
* Params:
* mode = (optional) Mode to use for decoding. (Defaults to LOOSE).
*
* Throws: DecodeException if decode fails
*/
string text(DecodeMode mode=DecodeMode.LOOSE)
{
string buffer;
foreach(item;items)
{
Text t = cast(Text)item;
if (t is null) throw new DecodeException(item.toString);
buffer ~= decode(t.toString,mode);
}
return buffer;
}
/**
* Returns an indented string representation of this item
*
* Params:
* indent = (optional) number of spaces by which to indent this
* element. Defaults to 2.
*/
override string[] pretty(uint indent=2)
{
if (isEmptyXML || tag.isEmpty) return [ tag.toEmptyString ];
if (items.length == 1)
{
Text t = cast(Text)(items[0]);
if (t !is null)
{
return [tag.toStartString ~ t.toString ~ tag.toEndString];
}
}
string[] a = [ tag.toStartString ];
foreach(item;items)
{
string[] b = item.pretty(indent);
foreach(s;b)
{
a ~= rightJustify(s,count(s) + indent);
}
}
a ~= tag.toEndString;
return a;
}
/**
* Returns the string representation of an Element
*