-
Notifications
You must be signed in to change notification settings - Fork 0
/
XMLToDictBuilder.m
55 lines (46 loc) · 1.8 KB
/
XMLToDictBuilder.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
//
// XMLToDictBuilder.m
// SSDP Browser
//
// Created by Thomas Tempelmann on 21.04.24.
// Copyright © 2024 Thomas Tempelmann. All rights reserved.
//
#import "XMLToDictBuilder.h"
@interface XMLToDictBuilder() <NSXMLParserDelegate>
@property NSXMLParser *parser;
@property NSMutableDictionary *dict;
@property NSMutableDictionary *currentNode;
@property NSMutableArray<NSMutableDictionary*> *nodeStack;
@property NSMutableString *collectedText;
@end
@implementation XMLToDictBuilder
- (NSDictionary*)parseData:(NSData*)data {
self.parser = [NSXMLParser.alloc initWithData:data];
self.parser.delegate = self;
[self.parser parse];
return self.dict;
}
-(void)parserDidStartDocument:(NSXMLParser *)parser {
self.dict = NSMutableDictionary.new;
self.nodeStack = NSMutableArray.new;
self.currentNode = self.dict;
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
self.collectedText = NSMutableString.new;
NSMutableDictionary *newNode = NSMutableDictionary.new;
self.currentNode[elementName] = newNode;
[self.nodeStack addObject:self.currentNode];
self.currentNode = newNode;
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
BOOL isEmptyNode = self.currentNode.count == 0;
self.currentNode = self.nodeStack.lastObject;
[self.nodeStack removeLastObject];
if (isEmptyNode && self.collectedText.length > 0) {
self.currentNode[elementName] = self.collectedText;
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
[self.collectedText appendString:[string stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet]];
}
@end