-
Notifications
You must be signed in to change notification settings - Fork 0
/
GDataXMLNode.m
1830 lines (1414 loc) · 58.3 KB
/
GDataXMLNode.m
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
/* Copyright (c) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define GDATAXMLNODE_DEFINE_GLOBALS 1
#import "GDataXMLNode.h"
@class NSArray, NSDictionary, NSError, NSString, NSURL;
@class GDataXMLElement, GDataXMLDocument;
static const int kGDataXMLParseOptions = (XML_PARSE_NOCDATA | XML_PARSE_NOBLANKS);
// dictionary key callbacks for string cache
static const void *StringCacheKeyRetainCallBack(CFAllocatorRef allocator, const void *str);
static void StringCacheKeyReleaseCallBack(CFAllocatorRef allocator, const void *str);
static CFStringRef StringCacheKeyCopyDescriptionCallBack(const void *str);
static Boolean StringCacheKeyEqualCallBack(const void *str1, const void *str2);
static CFHashCode StringCacheKeyHashCallBack(const void *str);
// isEqual: has the fatal flaw that it doesn't deal well with the received
// being nil. We'll use this utility instead.
// Static copy of AreEqualOrBothNil from GDataObject.m, so that using
// GDataXMLNode does not require pulling in all of GData.
static BOOL AreEqualOrBothNilPrivate(id obj1, id obj2) {
if (obj1 == obj2) {
return YES;
}
if (obj1 && obj2) {
return [obj1 isEqual:obj2];
}
return NO;
}
// convert NSString* to xmlChar*
//
// the "Get" part implies that ownership remains with str
static xmlChar* GDataGetXMLString(NSString *str) {
xmlChar* result = (xmlChar *)[str UTF8String];
return result;
}
// Make a fake qualified name we use as local name internally in libxml
// data structures when there's no actual namespace node available to point to
// from an element or attribute node
//
// Returns an autoreleased NSString*
static NSString *GDataFakeQNameForURIAndName(NSString *theURI, NSString *name) {
NSString *localName = [GDataXMLNode localNameForName:name];
NSString *fakeQName = [NSString stringWithFormat:@"{%@}:%@",
theURI, localName];
return fakeQName;
}
// libxml2 offers xmlSplitQName2, but that searches forwards. Since we may
// be searching for a whole URI shoved in as a prefix, like
// {http://foo}:name
// we'll search for the prefix in backwards from the end of the qualified name
//
// returns a copy of qname as the local name if there's no prefix
static xmlChar *SplitQNameReverse(const xmlChar *qname, xmlChar **prefix) {
// search backwards for a colon
int qnameLen = xmlStrlen(qname);
for (int idx = qnameLen - 1; idx >= 0; idx--) {
if (qname[idx] == ':') {
// found the prefix; copy the prefix, if requested
if (prefix != NULL) {
if (idx > 0) {
*prefix = xmlStrsub(qname, 0, idx);
} else {
*prefix = NULL;
}
}
if (idx < qnameLen - 1) {
// return a copy of the local name
xmlChar *localName = xmlStrsub(qname, idx + 1, qnameLen - idx - 1);
return localName;
} else {
return NULL;
}
}
}
// no colon found, so the qualified name is the local name
xmlChar *qnameCopy = xmlStrdup(qname);
return qnameCopy;
}
@interface GDataXMLNode (PrivateMethods)
// consuming a node implies it will later be freed when the instance is
// dealloc'd; borrowing it implies that ownership and disposal remain the
// job of the supplier of the node
+ (id)nodeConsumingXMLNode:(xmlNodePtr)theXMLNode;
- (id)initConsumingXMLNode:(xmlNodePtr)theXMLNode;
+ (id)nodeBorrowingXMLNode:(xmlNodePtr)theXMLNode;
- (id)initBorrowingXMLNode:(xmlNodePtr)theXMLNode;
// getters of the underlying node
- (xmlNodePtr)XMLNode;
- (xmlNodePtr)XMLNodeCopy;
// search for an underlying attribute
- (GDataXMLNode *)attributeForXMLNode:(xmlAttrPtr)theXMLNode;
// return an NSString for an xmlChar*, using our strings cache in the
// document
- (NSString *)stringFromXMLString:(const xmlChar *)chars;
// setter/getter of the dealloc flag for the underlying node
- (BOOL)shouldFreeXMLNode;
- (void)setShouldFreeXMLNode:(BOOL)flag;
@end
@interface GDataXMLElement (PrivateMethods)
+ (void)fixUpNamespacesForNode:(xmlNodePtr)nodeToFix
graftingToTreeNode:(xmlNodePtr)graftPointNode;
@end
@implementation GDataXMLNode
+ (void)load {
xmlInitParser();
}
// Note on convenience methods for making stand-alone element and
// attribute nodes:
//
// Since we're making a node from scratch, we don't
// have any namespace info. So the namespace prefix, if
// any, will just be slammed into the node name.
// We'll rely on the -addChild method below to remove
// the namespace prefix and replace it with a proper ns
// pointer.
+ (GDataXMLElement *)elementWithName:(NSString *)name {
xmlNodePtr theNewNode = xmlNewNode(NULL, // namespace
GDataGetXMLString(name));
if (theNewNode) {
// succeeded
return [self nodeConsumingXMLNode:theNewNode];
}
return nil;
}
+ (GDataXMLElement *)elementWithName:(NSString *)name stringValue:(NSString *)value {
xmlNodePtr theNewNode = xmlNewNode(NULL, // namespace
GDataGetXMLString(name));
if (theNewNode) {
xmlNodePtr textNode = xmlNewText(GDataGetXMLString(value));
if (textNode) {
xmlNodePtr temp = xmlAddChild(theNewNode, textNode);
if (temp) {
// succeeded
return [self nodeConsumingXMLNode:theNewNode];
}
}
// failed; free the node and any children
xmlFreeNode(theNewNode);
}
return nil;
}
+ (GDataXMLElement *)elementWithName:(NSString *)name URI:(NSString *)theURI {
// since we don't know a prefix yet, shove in the whole URI; we'll look for
// a proper namespace ptr later when addChild calls fixUpNamespacesForNode
NSString *fakeQName = GDataFakeQNameForURIAndName(theURI, name);
xmlNodePtr theNewNode = xmlNewNode(NULL, // namespace
GDataGetXMLString(fakeQName));
if (theNewNode) {
return [self nodeConsumingXMLNode:theNewNode];
}
return nil;
}
+ (id)attributeWithName:(NSString *)name stringValue:(NSString *)value {
xmlChar *xmlName = GDataGetXMLString(name);
xmlChar *xmlValue = GDataGetXMLString(value);
xmlAttrPtr theNewAttr = xmlNewProp(NULL, // parent node for the attr
xmlName, xmlValue);
if (theNewAttr) {
return [self nodeConsumingXMLNode:(xmlNodePtr) theNewAttr];
}
return nil;
}
+ (id)attributeWithName:(NSString *)name URI:(NSString *)attributeURI stringValue:(NSString *)value {
// since we don't know a prefix yet, shove in the whole URI; we'll look for
// a proper namespace ptr later when addChild calls fixUpNamespacesForNode
NSString *fakeQName = GDataFakeQNameForURIAndName(attributeURI, name);
xmlChar *xmlName = GDataGetXMLString(fakeQName);
xmlChar *xmlValue = GDataGetXMLString(value);
xmlAttrPtr theNewAttr = xmlNewProp(NULL, // parent node for the attr
xmlName, xmlValue);
if (theNewAttr) {
return [self nodeConsumingXMLNode:(xmlNodePtr) theNewAttr];
}
return nil;
}
+ (id)textWithStringValue:(NSString *)value {
xmlNodePtr theNewText = xmlNewText(GDataGetXMLString(value));
if (theNewText) {
return [self nodeConsumingXMLNode:theNewText];
}
return nil;
}
+ (id)namespaceWithName:(NSString *)name stringValue:(NSString *)value {
xmlChar *href = GDataGetXMLString(value);
xmlChar *prefix;
if ([name length] > 0) {
prefix = GDataGetXMLString(name);
} else {
// default namespace is represented by a nil prefix
prefix = nil;
}
xmlNsPtr theNewNs = xmlNewNs(NULL, // parent node
href, prefix);
if (theNewNs) {
return [self nodeConsumingXMLNode:(xmlNodePtr) theNewNs];
}
return nil;
}
+ (id)nodeConsumingXMLNode:(xmlNodePtr)theXMLNode {
Class theClass;
if (theXMLNode->type == XML_ELEMENT_NODE) {
theClass = [GDataXMLElement class];
} else {
theClass = [GDataXMLNode class];
}
return [[[theClass alloc] initConsumingXMLNode:theXMLNode] autorelease];
}
- (id)initConsumingXMLNode:(xmlNodePtr)theXMLNode {
self = [super init];
if (self) {
xmlNode_ = theXMLNode;
shouldFreeXMLNode_ = YES;
}
return self;
}
+ (id)nodeBorrowingXMLNode:(xmlNodePtr)theXMLNode {
Class theClass;
if (theXMLNode->type == XML_ELEMENT_NODE) {
theClass = [GDataXMLElement class];
} else {
theClass = [GDataXMLNode class];
}
return [[[theClass alloc] initBorrowingXMLNode:theXMLNode] autorelease];
}
- (id)initBorrowingXMLNode:(xmlNodePtr)theXMLNode {
self = [super init];
if (self) {
xmlNode_ = theXMLNode;
shouldFreeXMLNode_ = NO;
}
return self;
}
- (void)releaseCachedValues {
[cachedName_ release];
cachedName_ = nil;
[cachedChildren_ release];
cachedChildren_ = nil;
[cachedAttributes_ release];
cachedAttributes_ = nil;
}
// convert xmlChar* to NSString*
//
// returns an autoreleased NSString*, from the current node's document strings
// cache if possible
- (NSString *)stringFromXMLString:(const xmlChar *)chars {
#if DEBUG
NSCAssert(chars != NULL, @"GDataXMLNode sees an unexpected empty string");
#endif
if (chars == NULL) return nil;
CFMutableDictionaryRef cacheDict = NULL;
NSString *result = nil;
if (xmlNode_ != NULL
&& (xmlNode_->type == XML_ELEMENT_NODE
|| xmlNode_->type == XML_ATTRIBUTE_NODE
|| xmlNode_->type == XML_TEXT_NODE)) {
// there is no xmlDocPtr in XML_NAMESPACE_DECL nodes,
// so we can't cache the text of those
// look for a strings cache in the document
//
// the cache is in the document's user-defined _private field
if (xmlNode_->doc != NULL) {
cacheDict = xmlNode_->doc->_private;
if (cacheDict) {
// this document has a strings cache
result = (NSString *) CFDictionaryGetValue(cacheDict, chars);
if (result) {
// we found the xmlChar string in the cache; return the previously
// allocated NSString, rather than allocate a new one
return result;
}
}
}
}
// allocate a new NSString for this xmlChar*
result = [NSString stringWithUTF8String:(const char *) chars];
if (cacheDict) {
// save the string in the document's string cache
CFDictionarySetValue(cacheDict, chars, result);
}
return result;
}
- (void)dealloc {
if (xmlNode_ && shouldFreeXMLNode_) {
xmlFreeNode(xmlNode_);
xmlNode_ = NULL;
}
[self releaseCachedValues];
[super dealloc];
}
#pragma mark -
- (void)setStringValue:(NSString *)str {
if (xmlNode_ != NULL && str != nil) {
if (xmlNode_->type == XML_NAMESPACE_DECL) {
// for a namespace node, the value is the namespace URI
xmlNsPtr nsNode = (xmlNsPtr)xmlNode_;
if (nsNode->href != NULL) xmlFree((char *)nsNode->href);
nsNode->href = xmlStrdup(GDataGetXMLString(str));
} else {
// attribute or element node
// do we need to call xmlEncodeSpecialChars?
xmlNodeSetContent(xmlNode_, GDataGetXMLString(str));
}
}
}
- (NSString *)stringValue {
NSString *str = nil;
if (xmlNode_ != NULL) {
if (xmlNode_->type == XML_NAMESPACE_DECL) {
// for a namespace node, the value is the namespace URI
xmlNsPtr nsNode = (xmlNsPtr)xmlNode_;
str = [self stringFromXMLString:(nsNode->href)];
} else {
// attribute or element node
xmlChar* chars = xmlNodeGetContent(xmlNode_);
if (chars) {
str = [self stringFromXMLString:chars];
xmlFree(chars);
}
}
}
return str;
}
- (NSString *)XMLString {
NSString *str = nil;
if (xmlNode_ != NULL) {
xmlBufferPtr buff = xmlBufferCreate();
if (buff) {
xmlDocPtr doc = NULL;
int level = 0;
int format = 0;
int result = xmlNodeDump(buff, doc, xmlNode_, level, format);
if (result > -1) {
str = [[[NSString alloc] initWithBytes:(xmlBufferContent(buff))
length:(NSUInteger)(xmlBufferLength(buff))
encoding:NSUTF8StringEncoding] autorelease];
}
xmlBufferFree(buff);
}
}
// remove leading and trailing whitespace
NSCharacterSet *ws = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSString *trimmed = [str stringByTrimmingCharactersInSet:ws];
return trimmed;
}
- (NSString *)localName {
NSString *str = nil;
if (xmlNode_ != NULL) {
str = [self stringFromXMLString:(xmlNode_->name)];
// if this is part of a detached subtree, str may have a prefix in it
str = [[self class] localNameForName:str];
}
return str;
}
- (NSString *)prefix {
NSString *str = nil;
if (xmlNode_ != NULL) {
// the default namespace's prefix is an empty string, though libxml
// represents it as NULL for ns->prefix
str = @"";
if (xmlNode_->ns != NULL && xmlNode_->ns->prefix != NULL) {
str = [self stringFromXMLString:(xmlNode_->ns->prefix)];
}
}
return str;
}
- (NSString *)URI {
NSString *str = nil;
if (xmlNode_ != NULL) {
if (xmlNode_->ns != NULL && xmlNode_->ns->href != NULL) {
str = [self stringFromXMLString:(xmlNode_->ns->href)];
}
}
return str;
}
- (NSString *)qualifiedName {
// internal utility
NSString *str = nil;
if (xmlNode_ != NULL) {
if (xmlNode_->type == XML_NAMESPACE_DECL) {
// name of a namespace node
xmlNsPtr nsNode = (xmlNsPtr)xmlNode_;
// null is the default namespace; one is the loneliest number
if (nsNode->prefix == NULL) {
str = @"";
}
else {
str = [self stringFromXMLString:(nsNode->prefix)];
}
} else if (xmlNode_->ns != NULL && xmlNode_->ns->prefix != NULL) {
// name of a non-namespace node
// has a prefix
char *qname;
if (asprintf(&qname, "%s:%s", (const char *)xmlNode_->ns->prefix,
xmlNode_->name) != -1) {
str = [self stringFromXMLString:(const xmlChar *)qname];
free(qname);
}
} else {
// lacks a prefix
str = [self stringFromXMLString:(xmlNode_->name)];
}
}
return str;
}
- (NSString *)name {
if (cachedName_ != nil) {
return cachedName_;
}
NSString *str = [self qualifiedName];
cachedName_ = [str retain];
return str;
}
+ (NSString *)localNameForName:(NSString *)name {
if (name != nil) {
NSRange range = [name rangeOfString:@":"];
if (range.location != NSNotFound) {
// found a colon
if (range.location + 1 < [name length]) {
NSString *localName = [name substringFromIndex:(range.location + 1)];
return localName;
}
}
}
return name;
}
+ (NSString *)prefixForName:(NSString *)name {
if (name != nil) {
NSRange range = [name rangeOfString:@":"];
if (range.location != NSNotFound) {
NSString *prefix = [name substringToIndex:(range.location)];
return prefix;
}
}
return nil;
}
- (NSUInteger)childCount {
if (cachedChildren_ != nil) {
return [cachedChildren_ count];
}
if (xmlNode_ != NULL) {
unsigned int count = 0;
xmlNodePtr currChild = xmlNode_->children;
while (currChild != NULL) {
++count;
currChild = currChild->next;
}
return count;
}
return 0;
}
- (NSArray *)children {
if (cachedChildren_ != nil) {
return cachedChildren_;
}
NSMutableArray *array = nil;
if (xmlNode_ != NULL) {
xmlNodePtr currChild = xmlNode_->children;
while (currChild != NULL) {
GDataXMLNode *node = [GDataXMLNode nodeBorrowingXMLNode:currChild];
if (array == nil) {
array = [NSMutableArray arrayWithObject:node];
} else {
[array addObject:node];
}
currChild = currChild->next;
}
cachedChildren_ = [array retain];
}
return array;
}
- (GDataXMLNode *)childAtIndex:(unsigned)index {
NSArray *children = [self children];
if ([children count] > index) {
return [children objectAtIndex:index];
}
return nil;
}
- (GDataXMLNodeKind)kind {
if (xmlNode_ != NULL) {
xmlElementType nodeType = xmlNode_->type;
switch (nodeType) {
case XML_ELEMENT_NODE: return GDataXMLElementKind;
case XML_ATTRIBUTE_NODE: return GDataXMLAttributeKind;
case XML_TEXT_NODE: return GDataXMLTextKind;
case XML_CDATA_SECTION_NODE: return GDataXMLTextKind;
case XML_ENTITY_REF_NODE: return GDataXMLEntityDeclarationKind;
case XML_ENTITY_NODE: return GDataXMLEntityDeclarationKind;
case XML_PI_NODE: return GDataXMLProcessingInstructionKind;
case XML_COMMENT_NODE: return GDataXMLCommentKind;
case XML_DOCUMENT_NODE: return GDataXMLDocumentKind;
case XML_DOCUMENT_TYPE_NODE: return GDataXMLDocumentKind;
case XML_DOCUMENT_FRAG_NODE: return GDataXMLDocumentKind;
case XML_NOTATION_NODE: return GDataXMLNotationDeclarationKind;
case XML_HTML_DOCUMENT_NODE: return GDataXMLDocumentKind;
case XML_DTD_NODE: return GDataXMLDTDKind;
case XML_ELEMENT_DECL: return GDataXMLElementDeclarationKind;
case XML_ATTRIBUTE_DECL: return GDataXMLAttributeDeclarationKind;
case XML_ENTITY_DECL: return GDataXMLEntityDeclarationKind;
case XML_NAMESPACE_DECL: return GDataXMLNamespaceKind;
case XML_XINCLUDE_START: return GDataXMLProcessingInstructionKind;
case XML_XINCLUDE_END: return GDataXMLProcessingInstructionKind;
case XML_DOCB_DOCUMENT_NODE: return GDataXMLDocumentKind;
}
}
return GDataXMLInvalidKind;
}
- (NSArray *)nodesForXPath:(NSString *)xpath error:(NSError **)error {
// call through with no explicit namespace dictionary; that will register the
// root node's namespaces
return [self nodesForXPath:xpath namespaces:nil error:error];
}
- (NSArray *)nodesForXPath:(NSString *)xpath
namespaces:(NSDictionary *)namespaces
error:(NSError **)error {
NSMutableArray *array = nil;
NSInteger errorCode = -1;
NSDictionary *errorInfo = nil;
// xmlXPathNewContext requires a doc for its context, but if our elements
// are created from GDataXMLElement's initWithXMLString there may not be
// a document. (We may later decide that we want to stuff the doc used
// there into a GDataXMLDocument and retain it, but we don't do that now.)
//
// We'll temporarily make a document to use for the xpath context.
xmlDocPtr tempDoc = NULL;
xmlNodePtr topParent = NULL;
if (xmlNode_->doc == NULL) {
tempDoc = xmlNewDoc(NULL);
if (tempDoc) {
// find the topmost node of the current tree to make the root of
// our temporary document
topParent = xmlNode_;
while (topParent->parent != NULL) {
topParent = topParent->parent;
}
xmlDocSetRootElement(tempDoc, topParent);
}
}
if (xmlNode_ != NULL && xmlNode_->doc != NULL) {
xmlXPathContextPtr xpathCtx = xmlXPathNewContext(xmlNode_->doc);
if (xpathCtx) {
// anchor at our current node
xpathCtx->node = xmlNode_;
// if a namespace dictionary was provided, register its contents
if (namespaces) {
// the dictionary keys are prefixes; the values are URIs
for (NSString *prefix in namespaces) {
NSString *uri = [namespaces objectForKey:prefix];
xmlChar *prefixChars = (xmlChar *) [prefix UTF8String];
xmlChar *uriChars = (xmlChar *) [uri UTF8String];
int result = xmlXPathRegisterNs(xpathCtx, prefixChars, uriChars);
if (result != 0) {
#if DEBUG
NSCAssert1(result == 0, @"GDataXMLNode XPath namespace %@ issue",
prefix);
#endif
}
}
} else {
// no namespace dictionary was provided
//
// register the namespaces of this node, if it's an element, or of
// this node's root element, if it's a document
xmlNodePtr nsNodePtr = xmlNode_;
if (xmlNode_->type == XML_DOCUMENT_NODE) {
nsNodePtr = xmlDocGetRootElement((xmlDocPtr) xmlNode_);
}
// step through the namespaces, if any, and register each with the
// xpath context
if (nsNodePtr != NULL) {
for (xmlNsPtr nsPtr = nsNodePtr->ns; nsPtr != NULL; nsPtr = nsPtr->next) {
// default namespace is nil in the tree, but there's no way to
// register a default namespace, so we'll register a fake one,
// _def_ns
const xmlChar* prefix = nsPtr->prefix;
if (prefix == NULL) {
prefix = (xmlChar*) kGDataXMLXPathDefaultNamespacePrefix;
}
int result = xmlXPathRegisterNs(xpathCtx, prefix, nsPtr->href);
if (result != 0) {
#if DEBUG
NSCAssert1(result == 0, @"GDataXMLNode XPath namespace %s issue",
prefix);
#endif
}
}
}
}
// now evaluate the path
xmlXPathObjectPtr xpathObj;
xpathObj = xmlXPathEval(GDataGetXMLString(xpath), xpathCtx);
if (xpathObj) {
// we have some result from the search
array = [NSMutableArray array];
xmlNodeSetPtr nodeSet = xpathObj->nodesetval;
if (nodeSet) {
// add each node in the result set to our array
for (int index = 0; index < nodeSet->nodeNr; index++) {
xmlNodePtr currNode = nodeSet->nodeTab[index];
GDataXMLNode *node = [GDataXMLNode nodeBorrowingXMLNode:currNode];
if (node) {
[array addObject:node];
}
}
}
xmlXPathFreeObject(xpathObj);
} else {
// provide an error for failed evaluation
const char *msg = xpathCtx->lastError.str1;
errorCode = xpathCtx->lastError.code;
if (msg) {
NSString *errStr = [NSString stringWithUTF8String:msg];
errorInfo = [NSDictionary dictionaryWithObject:errStr
forKey:@"error"];
}
}
xmlXPathFreeContext(xpathCtx);
}
} else {
// not a valid node for using XPath
errorInfo = [NSDictionary dictionaryWithObject:@"invalid node"
forKey:@"error"];
}
if (array == nil && error != nil) {
*error = [NSError errorWithDomain:@"com.google.GDataXML"
code:errorCode
userInfo:errorInfo];
}
if (tempDoc != NULL) {
xmlUnlinkNode(topParent);
xmlSetTreeDoc(topParent, NULL);
xmlFreeDoc(tempDoc);
}
return array;
}
- (NSString *)description {
int nodeType = (xmlNode_ ? (int)xmlNode_->type : -1);
return [NSString stringWithFormat:@"%@ %p: {type:%d name:%@ xml:\"%@\"}",
[self class], self, nodeType, [self name], [self XMLString]];
}
- (id)copyWithZone:(NSZone *)zone {
xmlNodePtr nodeCopy = [self XMLNodeCopy];
if (nodeCopy != NULL) {
return [[[self class] alloc] initConsumingXMLNode:nodeCopy];
}
return nil;
}
- (BOOL)isEqual:(GDataXMLNode *)other {
if (self == other) return YES;
if (![other isKindOfClass:[GDataXMLNode class]]) return NO;
return [self XMLNode] == [other XMLNode]
|| ([self kind] == [other kind]
&& AreEqualOrBothNilPrivate([self name], [other name])
&& [[self children] count] == [[other children] count]);
}
- (NSUInteger)hash {
return (NSUInteger) (void *) [GDataXMLNode class];
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector {
return [super methodSignatureForSelector:selector];
}
#pragma mark -
- (xmlNodePtr)XMLNodeCopy {
if (xmlNode_ != NULL) {
// Note: libxml will create a new copy of namespace nodes (xmlNs records)
// and attach them to this copy in order to keep namespaces within this
// node subtree copy value.
xmlNodePtr nodeCopy = xmlCopyNode(xmlNode_, 1); // 1 = recursive
return nodeCopy;
}
return NULL;
}
- (xmlNodePtr)XMLNode {
return xmlNode_;
}
- (BOOL)shouldFreeXMLNode {
return shouldFreeXMLNode_;
}
- (void)setShouldFreeXMLNode:(BOOL)flag {
shouldFreeXMLNode_ = flag;
}
@end
@implementation GDataXMLElement
- (id)initWithXMLString:(NSString *)str error:(NSError **)error {
self = [super init];
if (self) {
const char *utf8Str = [str UTF8String];
// NOTE: We are assuming a string length that fits into an int
xmlDocPtr doc = xmlReadMemory(utf8Str, (int)strlen(utf8Str), NULL, // URL
NULL, // encoding
kGDataXMLParseOptions);
if (doc == NULL) {
if (error) {
// TODO(grobbins) use xmlSetGenericErrorFunc to capture error
}
} else {
// copy the root node from the doc
xmlNodePtr root = xmlDocGetRootElement(doc);
if (root) {
xmlNode_ = xmlCopyNode(root, 1); // 1: recursive
shouldFreeXMLNode_ = YES;
}
xmlFreeDoc(doc);
}
if (xmlNode_ == NULL) {
// failure
if (error) {
*error = [NSError errorWithDomain:@"com.google.GDataXML"
code:-1
userInfo:nil];
}
[self release];
return nil;
}
}
return self;
}
- (NSArray *)namespaces {
NSMutableArray *array = nil;
if (xmlNode_ != NULL && xmlNode_->nsDef != NULL) {
xmlNsPtr currNS = xmlNode_->nsDef;
while (currNS != NULL) {
// add this prefix/URI to the list, unless it's the implicit xml prefix
if (!xmlStrEqual(currNS->prefix, (const xmlChar *) "xml")) {
GDataXMLNode *node = [GDataXMLNode nodeBorrowingXMLNode:(xmlNodePtr) currNS];
if (array == nil) {
array = [NSMutableArray arrayWithObject:node];
} else {
[array addObject:node];
}
}
currNS = currNS->next;
}
}
return array;
}
- (void)setNamespaces:(NSArray *)namespaces {
if (xmlNode_ != NULL) {
[self releaseCachedValues];
// remove previous namespaces
if (xmlNode_->nsDef) {
xmlFreeNsList(xmlNode_->nsDef);
xmlNode_->nsDef = NULL;
}
// add a namespace for each object in the array
NSEnumerator *enumerator = [namespaces objectEnumerator];
GDataXMLNode *namespaceNode;
while ((namespaceNode = [enumerator nextObject]) != nil) {
xmlNsPtr ns = (xmlNsPtr) [namespaceNode XMLNode];
if (ns) {
(void)xmlNewNs(xmlNode_, ns->href, ns->prefix);
}
}
// we may need to fix this node's own name; the graft point is where
// the namespace search starts, so that points to this node too
[[self class] fixUpNamespacesForNode:xmlNode_
graftingToTreeNode:xmlNode_];
}
}
- (void)addNamespace:(GDataXMLNode *)aNamespace {
if (xmlNode_ != NULL) {