views:

96

answers:

2

Hi,

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"&gt;
  <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] pathForResource:@"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

A: 

I think this is not a valid XML

NaveenShan
It is most certainly a valid xml, but just to be sure... [...] means that there is more code there but not necessary to put into the post.
Paul Peelen
+1  A: 

Hi Paul,

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?

Lee Armstrong