-1

I have already read about NSxmlparser. I have the following file, but I do not understand how I should do for the parser.

i Trying to parse xml list without parent node using NSxmlparser

<nodes1>
            <child1>txt1</child1>
            <child2>Txt2</child2>
</nodes1>
<nodes1>
            <child1>Txt3</child1>
            <child2>Txt4</child2>
</nodes1>
<nodes1>
            <child1>Txt5</child1>
            <child2>Txt6</child2>
</nodes1>
  • [What have you tried?](http://whathaveyoutried.com/) – rckoenes Mar 14 '13 at 13:49
  • I am in the process of development, but I plant what I should write here `- (void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementname namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { } ` – user214617 Mar 14 '13 at 13:53

1 Answers1

0

Get the file and start parsing

NSError *error;
NSString *xmlPath = [[NSBundle mainBundle] pathForResource:@"yourFile" ofType:@"xml"];

NSString* contents = [NSString stringWithContentsOfFile:xmlPath encoding:NSUTF8StringEncoding error:&error];
self.xmlData = [[NSData alloc] init];
self.xmlData = [contents dataUsingEncoding:NSUTF8StringEncoding];

self.xmlParser = [[NSXMLParser alloc] initWithData:self.xmlData];
[self.xmlParser setDelegate: self];
[self.xmlParser setShouldResolveExternalEntities: YES];
[self.xmlParser parse];

then for parsing

BOOL isValid_child1 = NO;

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName attributes: (NSDictionary *)attributeDict
{
      if ([elementName isEqualToString:@"child1"]) {
      isValid_child1 = YES; 
      }
}

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if (isValid_child1) {
        valueInChild1 = string; // string is txt1
}

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if ([elementName isEqualToString:@"child1"]) {
       isValid_child1 = NO;
       [array addObject:valueInChild1]; // to add value for child1 to an array
    }

I know this is dirty ;) but it works, you can do it more flexible.

Retterdesdialogs
  • 3,180
  • 1
  • 21
  • 42