OSSXMLDictionary.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. //
  2. // XMLDictionary.m
  3. //
  4. // Version 1.4
  5. //
  6. // Created by Nick Lockwood on 15/11/2010.
  7. // Copyright 2010 Charcoal Design. All rights reserved.
  8. //
  9. // Get the latest version of XMLDictionary from here:
  10. //
  11. // https://github.com/nicklockwood/XMLDictionary
  12. //
  13. // This software is provided 'as-is', without any express or implied
  14. // warranty. In no event will the authors be held liable for any damages
  15. // arising from the use of this software.
  16. //
  17. // Permission is granted to anyone to use this software for any purpose,
  18. // including commercial applications, and to alter it and redistribute it
  19. // freely, subject to the following restrictions:
  20. //
  21. // 1. The origin of this software must not be misrepresented; you must not
  22. // claim that you wrote the original software. If you use this software
  23. // in a product, an acknowledgment in the product documentation would be
  24. // appreciated but is not required.
  25. //
  26. // 2. Altered source versions must be plainly marked as such, and must not be
  27. // misrepresented as being the original software.
  28. //
  29. // 3. This notice may not be removed or altered from any source distribution.
  30. //
  31. #import "OSSXMLDictionary.h"
  32. #pragma GCC diagnostic ignored "-Wobjc-missing-property-synthesis"
  33. #pragma GCC diagnostic ignored "-Wdirect-ivar-access"
  34. #pragma GCC diagnostic ignored "-Wformat-non-iso"
  35. #pragma GCC diagnostic ignored "-Wgnu"
  36. #import <Availability.h>
  37. #if !__has_feature(objc_arc)
  38. #error This class requires automatic reference counting
  39. #endif
  40. @interface OSSXMLDictionaryParser () <NSXMLParserDelegate>
  41. @property (nonatomic, strong) NSMutableDictionary *root;
  42. @property (nonatomic, strong) NSMutableArray *stack;
  43. @property (nonatomic, strong) NSMutableString *text;
  44. @end
  45. @implementation OSSXMLDictionaryParser
  46. - (id)init
  47. {
  48. if ((self = [super init]))
  49. {
  50. _collapseTextNodes = YES;
  51. _stripEmptyNodes = YES;
  52. _trimWhiteSpace = YES;
  53. _alwaysUseArrays = NO;
  54. _preserveComments = NO;
  55. _wrapRootNode = NO;
  56. }
  57. return self;
  58. }
  59. - (id)copyWithZone:(NSZone *)zone
  60. {
  61. OSSXMLDictionaryParser *copy = [[[self class] allocWithZone:zone] init];
  62. copy.collapseTextNodes = _collapseTextNodes;
  63. copy.stripEmptyNodes = _stripEmptyNodes;
  64. copy.trimWhiteSpace = _trimWhiteSpace;
  65. copy.alwaysUseArrays = _alwaysUseArrays;
  66. copy.preserveComments = _preserveComments;
  67. copy.attributesMode = _attributesMode;
  68. copy.nodeNameMode = _nodeNameMode;
  69. copy.wrapRootNode = _wrapRootNode;
  70. return copy;
  71. }
  72. #pragma mark - Public Methods
  73. + (OSSXMLDictionaryParser *)sharedInstance
  74. {
  75. static dispatch_once_t once;
  76. static OSSXMLDictionaryParser *sharedInstance;
  77. dispatch_once(&once, ^{
  78. sharedInstance = [[OSSXMLDictionaryParser alloc] init];
  79. });
  80. return sharedInstance;
  81. }
  82. - (NSDictionary *)dictionaryWithParser:(NSXMLParser *)parser
  83. {
  84. [parser setDelegate:self];
  85. BOOL succeed = [parser parse];
  86. #ifdef DEBUG
  87. NSLog(@"dictionaryWithParser %@",(succeed?@"YES":@"NO"));
  88. #endif
  89. id result = _root;
  90. _root = nil;
  91. _stack = nil;
  92. _text = nil;
  93. return result;
  94. }
  95. - (NSDictionary *)dictionaryWithData:(NSData *)data
  96. {
  97. NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
  98. return [self dictionaryWithParser:parser];
  99. }
  100. - (NSDictionary *)dictionaryWithString:(NSString *)string
  101. {
  102. NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
  103. return [self dictionaryWithData:data];
  104. }
  105. - (NSDictionary *)dictionaryWithFile:(NSString *)path
  106. {
  107. NSData *data = [NSData dataWithContentsOfFile:path];
  108. return [self dictionaryWithData:data];
  109. }
  110. #pragma mark - Private Methods
  111. + (NSString *)XMLStringForNode:(id)node withNodeName:(NSString *)nodeName
  112. {
  113. if ([node isKindOfClass:[NSArray class]])
  114. {
  115. NSMutableArray *nodes = [NSMutableArray arrayWithCapacity:[node count]];
  116. for (id individualNode in node)
  117. {
  118. [nodes addObject:[self XMLStringForNode:individualNode withNodeName:nodeName]];
  119. }
  120. return [nodes componentsJoinedByString:@"\n"];
  121. }
  122. else if ([node isKindOfClass:[NSDictionary class]])
  123. {
  124. NSDictionary *attributes = [(NSDictionary *)node oss_attributes];
  125. NSMutableString *attributeString = [NSMutableString string];
  126. for (NSString *key in [attributes allKeys])
  127. {
  128. [attributeString appendFormat:@" %@=\"%@\"", [[key description] oss_XMLEncodedString], [[attributes[key] description] oss_XMLEncodedString]];
  129. }
  130. NSString *innerXML = [node oss_innerXML];
  131. if ([innerXML length])
  132. {
  133. return [NSString stringWithFormat:@"<%1$@%2$@>%3$@</%1$@>", nodeName, attributeString, innerXML];
  134. }
  135. else
  136. {
  137. return [NSString stringWithFormat:@"<%@%@/>", nodeName, attributeString];
  138. }
  139. }
  140. else
  141. {
  142. return [NSString stringWithFormat:@"<%1$@>%2$@</%1$@>", nodeName, [[node description] oss_XMLEncodedString]];
  143. }
  144. }
  145. - (void)endText
  146. {
  147. if (_trimWhiteSpace)
  148. {
  149. _text = [[_text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] mutableCopy];
  150. }
  151. if ([_text length])
  152. {
  153. NSMutableDictionary *top = [_stack lastObject];
  154. id existing = top[OSSXMLDictionaryTextKey];
  155. if ([existing isKindOfClass:[NSArray class]])
  156. {
  157. [existing addObject:_text];
  158. }
  159. else if (existing)
  160. {
  161. top[OSSXMLDictionaryTextKey] = [@[existing, _text] mutableCopy];
  162. }
  163. else
  164. {
  165. top[OSSXMLDictionaryTextKey] = _text;
  166. }
  167. }
  168. _text = nil;
  169. }
  170. - (void)addText:(NSString *)text
  171. {
  172. if (!_text)
  173. {
  174. _text = [NSMutableString stringWithString:text];
  175. }
  176. else
  177. {
  178. [_text appendString:text];
  179. }
  180. }
  181. - (NSString *)nameForNode:(NSDictionary *)node inDictionary:(NSDictionary *)dict
  182. {
  183. if (node.oss_nodeName)
  184. {
  185. return node.oss_nodeName;
  186. }
  187. else
  188. {
  189. for (NSString *name in dict)
  190. {
  191. id object = dict[name];
  192. if (object == node)
  193. {
  194. return name;
  195. }
  196. else if ([object isKindOfClass:[NSArray class]] && [object containsObject:node])
  197. {
  198. return name;
  199. }
  200. }
  201. }
  202. return nil;
  203. }
  204. #pragma mark - NSXMLParserDelegate mehods
  205. - (void)parser:(__unused NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(__unused NSString *)namespaceURI qualifiedName:(__unused NSString *)qName attributes:(NSDictionary *)attributeDict
  206. {
  207. [self endText];
  208. NSMutableDictionary *node = [NSMutableDictionary dictionary];
  209. switch (_nodeNameMode)
  210. {
  211. case OSSXMLDictionaryNodeNameModeRootOnly:
  212. {
  213. if (!_root)
  214. {
  215. node[OSSXMLDictionaryNodeNameKey] = elementName;
  216. }
  217. break;
  218. }
  219. case OSSXMLDictionaryNodeNameModeAlways:
  220. {
  221. node[OSSXMLDictionaryNodeNameKey] = elementName;
  222. break;
  223. }
  224. case OSSXMLDictionaryNodeNameModeNever:
  225. {
  226. break;
  227. }
  228. }
  229. if ([attributeDict count])
  230. {
  231. switch (_attributesMode)
  232. {
  233. case OSSXMLDictionaryAttributesModePrefixed:
  234. {
  235. for (NSString *key in [attributeDict allKeys])
  236. {
  237. node[[OSSXMLDictionaryAttributePrefix stringByAppendingString:key]] = attributeDict[key];
  238. }
  239. break;
  240. }
  241. case OSSXMLDictionaryAttributesModeDictionary:
  242. {
  243. node[OSSXMLDictionaryAttributesKey] = attributeDict;
  244. break;
  245. }
  246. case OSSXMLDictionaryAttributesModeUnprefixed:
  247. {
  248. [node addEntriesFromDictionary:attributeDict];
  249. break;
  250. }
  251. case OSSXMLDictionaryAttributesModeDiscard:
  252. {
  253. break;
  254. }
  255. }
  256. }
  257. if (!_root)
  258. {
  259. _root = node;
  260. _stack = [NSMutableArray arrayWithObject:node];
  261. if (_wrapRootNode)
  262. {
  263. _root = [NSMutableDictionary dictionaryWithObject:_root forKey:elementName];
  264. [_stack insertObject:_root atIndex:0];
  265. }
  266. }
  267. else
  268. {
  269. NSMutableDictionary *top = [_stack lastObject];
  270. id existing = top[elementName];
  271. if ([existing isKindOfClass:[NSArray class]])
  272. {
  273. [existing addObject:node];
  274. }
  275. else if (existing)
  276. {
  277. top[elementName] = [@[existing, node] mutableCopy];
  278. }
  279. else if (_alwaysUseArrays)
  280. {
  281. top[elementName] = [NSMutableArray arrayWithObject:node];
  282. }
  283. else
  284. {
  285. top[elementName] = node;
  286. }
  287. [_stack addObject:node];
  288. }
  289. }
  290. - (void)parser:(__unused NSXMLParser *)parser didEndElement:(__unused NSString *)elementName namespaceURI:(__unused NSString *)namespaceURI qualifiedName:(__unused NSString *)qName
  291. {
  292. [self endText];
  293. NSMutableDictionary *top = [_stack lastObject];
  294. [_stack removeLastObject];
  295. if (!top.oss_attributes && !top.oss_childNodes && !top.oss_comments)
  296. {
  297. NSMutableDictionary *newTop = [_stack lastObject];
  298. NSString *nodeName = [self nameForNode:top inDictionary:newTop];
  299. if (nodeName)
  300. {
  301. id parentNode = newTop[nodeName];
  302. if (top.oss_innerText && _collapseTextNodes)
  303. {
  304. if ([parentNode isKindOfClass:[NSArray class]])
  305. {
  306. parentNode[[parentNode count] - 1] = top.oss_innerText;
  307. }
  308. else
  309. {
  310. newTop[nodeName] = top.oss_innerText;
  311. }
  312. }
  313. else if (!top.oss_innerText && _stripEmptyNodes)
  314. {
  315. if ([parentNode isKindOfClass:[NSArray class]])
  316. {
  317. [parentNode removeLastObject];
  318. }
  319. else
  320. {
  321. [newTop removeObjectForKey:nodeName];
  322. }
  323. }
  324. else if (!top.oss_innerText && !_collapseTextNodes && !_stripEmptyNodes)
  325. {
  326. top[OSSXMLDictionaryTextKey] = @"";
  327. }
  328. }
  329. }
  330. }
  331. - (void)parser:(__unused NSXMLParser *)parser foundCharacters:(NSString *)string
  332. {
  333. [self addText:string];
  334. }
  335. - (void)parser:(__unused NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock
  336. {
  337. [self addText:[[NSString alloc] initWithData:CDATABlock encoding:NSUTF8StringEncoding]];
  338. }
  339. - (void)parser:(__unused NSXMLParser *)parser foundComment:(NSString *)comment
  340. {
  341. if (_preserveComments)
  342. {
  343. NSMutableDictionary *top = [_stack lastObject];
  344. NSMutableArray *comments = top[OSSXMLDictionaryCommentsKey];
  345. if (!comments)
  346. {
  347. comments = [@[comment] mutableCopy];
  348. top[OSSXMLDictionaryCommentsKey] = comments;
  349. }
  350. else
  351. {
  352. [comments addObject:comment];
  353. }
  354. }
  355. }
  356. @end
  357. @implementation NSDictionary(OSSXMLDictionary)
  358. + (NSDictionary *)oss_dictionaryWithXMLParser:(NSXMLParser *)parser
  359. {
  360. return [[[OSSXMLDictionaryParser sharedInstance] copy] dictionaryWithParser:parser];
  361. }
  362. + (NSDictionary *)oss_dictionaryWithXMLData:(NSData *)data
  363. {
  364. return [[[OSSXMLDictionaryParser sharedInstance] copy] dictionaryWithData:data];
  365. }
  366. + (NSDictionary *)oss_dictionaryWithXMLString:(NSString *)string
  367. {
  368. return [[[OSSXMLDictionaryParser sharedInstance] copy] dictionaryWithString:string];
  369. }
  370. + (NSDictionary *)oss_dictionaryWithXMLFile:(NSString *)path
  371. {
  372. return [[[OSSXMLDictionaryParser sharedInstance] copy] dictionaryWithFile:path];
  373. }
  374. - (NSDictionary *)oss_attributes
  375. {
  376. NSDictionary *attributes = self[OSSXMLDictionaryAttributesKey];
  377. if (attributes)
  378. {
  379. return [attributes count]? attributes: nil;
  380. }
  381. else
  382. {
  383. NSMutableDictionary *filteredDict = [NSMutableDictionary dictionaryWithDictionary:self];
  384. [filteredDict removeObjectsForKeys:@[OSSXMLDictionaryCommentsKey, OSSXMLDictionaryTextKey, OSSXMLDictionaryNodeNameKey]];
  385. for (NSString *key in [filteredDict allKeys])
  386. {
  387. [filteredDict removeObjectForKey:key];
  388. if ([key hasPrefix:OSSXMLDictionaryAttributePrefix])
  389. {
  390. filteredDict[[key substringFromIndex:[OSSXMLDictionaryAttributePrefix length]]] = self[key];
  391. }
  392. }
  393. return [filteredDict count]? filteredDict: nil;
  394. }
  395. return nil;
  396. }
  397. - (NSDictionary *)oss_childNodes
  398. {
  399. NSMutableDictionary *filteredDict = [self mutableCopy];
  400. [filteredDict removeObjectsForKeys:@[OSSXMLDictionaryAttributesKey, OSSXMLDictionaryCommentsKey, OSSXMLDictionaryTextKey, OSSXMLDictionaryNodeNameKey]];
  401. for (NSString *key in [filteredDict allKeys])
  402. {
  403. if ([key hasPrefix:OSSXMLDictionaryAttributePrefix])
  404. {
  405. [filteredDict removeObjectForKey:key];
  406. }
  407. }
  408. return [filteredDict count]? filteredDict: nil;
  409. }
  410. - (NSArray *)oss_comments
  411. {
  412. return self[OSSXMLDictionaryCommentsKey];
  413. }
  414. - (NSString *)oss_nodeName
  415. {
  416. return self[OSSXMLDictionaryNodeNameKey];
  417. }
  418. - (id)oss_innerText
  419. {
  420. id text = self[OSSXMLDictionaryTextKey];
  421. if ([text isKindOfClass:[NSArray class]])
  422. {
  423. return [text componentsJoinedByString:@"\n"];
  424. }
  425. else
  426. {
  427. return text;
  428. }
  429. }
  430. - (NSString *)oss_innerXML
  431. {
  432. NSMutableArray *nodes = [NSMutableArray array];
  433. for (NSString *comment in [self oss_comments])
  434. {
  435. [nodes addObject:[NSString stringWithFormat:@"<!--%@-->", [comment oss_XMLEncodedString]]];
  436. }
  437. NSDictionary *childNodes = [self oss_childNodes];
  438. for (NSString *key in childNodes)
  439. {
  440. [nodes addObject:[OSSXMLDictionaryParser XMLStringForNode:childNodes[key] withNodeName:key]];
  441. }
  442. NSString *text = [self oss_innerText];
  443. if (text)
  444. {
  445. [nodes addObject:[text oss_XMLEncodedString]];
  446. }
  447. return [nodes componentsJoinedByString:@"\n"];
  448. }
  449. - (NSString *)oss_XMLString
  450. {
  451. if ([self count] == 1 && ![self oss_nodeName])
  452. {
  453. //ignore outermost dictionary
  454. return [self oss_innerXML];
  455. }
  456. else
  457. {
  458. return [OSSXMLDictionaryParser XMLStringForNode:self withNodeName:[self oss_nodeName] ?: @"root"];
  459. }
  460. }
  461. - (NSArray *)oss_arrayValueForKeyPath:(NSString *)keyPath
  462. {
  463. id value = [self valueForKeyPath:keyPath];
  464. if (value && ![value isKindOfClass:[NSArray class]])
  465. {
  466. return @[value];
  467. }
  468. return value;
  469. }
  470. - (NSString *)oss_stringValueForKeyPath:(NSString *)keyPath
  471. {
  472. id value = [self valueForKeyPath:keyPath];
  473. if ([value isKindOfClass:[NSArray class]])
  474. {
  475. value = [value count]? value[0]: nil;
  476. }
  477. if ([value isKindOfClass:[NSDictionary class]])
  478. {
  479. return [(NSDictionary *)value oss_innerText];
  480. }
  481. return value;
  482. }
  483. - (NSDictionary *)oss_dictionaryValueForKeyPath:(NSString *)keyPath
  484. {
  485. id value = [self valueForKeyPath:keyPath];
  486. if ([value isKindOfClass:[NSArray class]])
  487. {
  488. value = [value count]? value[0]: nil;
  489. }
  490. if ([value isKindOfClass:[NSString class]])
  491. {
  492. return @{OSSXMLDictionaryTextKey: value};
  493. }
  494. return value;
  495. }
  496. @end
  497. @implementation NSString (OSSXMLDictionary)
  498. - (NSString *)oss_XMLEncodedString
  499. {
  500. return [[[[[self stringByReplacingOccurrencesOfString:@"&" withString:@"&amp;"]
  501. stringByReplacingOccurrencesOfString:@"<" withString:@"&lt;"]
  502. stringByReplacingOccurrencesOfString:@">" withString:@"&gt;"]
  503. stringByReplacingOccurrencesOfString:@"\"" withString:@"&quot;"]
  504. stringByReplacingOccurrencesOfString:@"\'" withString:@"&apos;"];
  505. }
  506. @end