views:

58

answers:

1

I'm parsing this line:

<type>branch</type>

with this code in didEndElement

if ([elementName isEqualToString:@"type"]) {

        [currentBranchDictionary setValue:currentText forKey:currentElementName];

    }

When I test the value in the type key, it does not contain branch but instead it contains branch\n. Here is the test I'm performing:

    if ([[currentBranchDictionary valueForKey:@"type"] isEqualToString:@"branch"]) {
        NSLog(@"no new-line");
    } else if ([[currentBranchDictionary valueForKey:@"type"] isEqualToString:@"branch\n"]) {
        NSLog(@"new-line");
    }

this returns the "new-line" output

Here's the foundCharacters method:

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    [currentText appendString:string];
}

I don't understand where the carriage return is being added, can anyone help?

+1  A: 

I suspect your XML contains carriage returns ("\r") that aren't being displayed by your editor. The XML specification requires these to be translated to line feeds ("\n") prior to reporting the result to your application:

http://www.w3.org/TR/REC-xml/#sec-line-ends

Can you verify the contents of your XML file? What is the output from the xxd command? Here's the output from a file I created. Note the extra 0d character:

0000000: 3c74 7970 653e 6272 616e 6368 0d3c 2f74  <type>branch.</t
0000010: 7970 653e                                ype>
bkail
Hi bkail, I hand-typed the lines containing `<type>branch</type>` and they do not have carriage returns. If I output `currentText` before I place its contents into the dictionary, it has no carriage return. If I output the `valueForKey:@"type"` immediately after setting it, it has no carriage return. However, if I output `valueForKey:@"type"` after I leave `didEndElement` it does have a carriage return. I don't understand why.
Griffo
I discovered the problem. The `\r` was after the closed element, for example `<type>branch</type>\r`. This meant that I was closing the element, calling `didEndElement` where I would output `currentText` and this would contain `branch`. However, then `foundCharacters` would be called for the `\r` at the end of the line. This would append the `\r` to `currentText` whose value was pointed to by `[currentBranchDictionary valueForKey:@"type"]`. QED
Griffo