开发者

NSString with XML to NSArray with NSDictionary

I have a small problem I can't seem to solve. I have a XML page with the following content:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfCategory xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://api.tradera.com">
  <Category Id="1612" Name="Category 1">
    <Category Id="161213" Name="Category 1 subcat 1">
      <Category Id="340761" Name="Category 1, subcat 1, subcat 1" />
      <Category Id="340761" Name="Category 1, subcat 1, subcat 2" />
      <Category Id="340761" Name="Category 1, subcat 1, subcat 3" />
      <Category Id="340761" Name="Category 1, subcat 1, subcat 4" />
      <Category Id="340761" Name="Category 1, subcat 1, subcat 5" />
    </Category>
    <Category Id="161213" Name="Category 1 subcat 2"></category>
    <Category Id="161213" Name="Category 1 subcat 3">
      <Category Id="340761" Name="Category 1, subcat 3, subcat 1" />
    </category>
  </Category>
  <Category Id="1612" Name="Category 1">
    [...]
  </category>
</ArrayOfCategory>

What I want to do is to convert this into an array with dictionaries. So, this sould be an array with key 0 = dictorionary with items Id, Name and subcats. Subcats should be an array with the same keys.

So far I have the following code:

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self startParsing];
}

- (void)startParsing {
    NSString *path = [[NSBundle mainBundle] pathFo开发者_JS百科rResource:@"categories" ofType:@"xml"];

    NSData *xmlData = [[NSData alloc] initWithContentsOfFile:path];
    NSXMLParser *parser = [[[NSXMLParser alloc] initWithData:xmlData] autorelease];
    [parser setDelegate:self];
    [parser parse];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
    NSLog(@"Started %@, attribute: %@", elementName, attributeDict);
}

But I can't seem to figure out how to create this array using NSXMLParser, any suggestions?

Best regards, Paul Peelen


As discussed on the chat you will need to track what level you are at inside the

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
    NSLog(@"Started %@, attribute: %@", elementName, attributeDict);
}

section. Possibly using a global ivar inside this?


A little lib allowing you to easily convert XML to NSDictionary:

https://github.com/bcaccinolo/XML-to-NSDictionary

Have fun !

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜