iosxmlnsxmlparser

Special characters in XML attributes with NSXMLParser


I get something like the following from a third party API:

<el attr="test.

another test." />

I use NSXMLParser to read the file into my app.

However, in the delegate, the attribute gets converted to test. another test. Obviously I'd like to see it with the line breaks intact.

I initially assumed that this was a bug but, according to the XML Spec it's doing the right thing:

a whitespace character (#x20, #xD, #xA, #x9) is processed by appending #x20 to the normalized value

(See section 3.3.3.)

What are my options? Note that it's a third party API so I can't change it, even though it's wrong.


Solution

  • NSData *xmlData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"url://"]];
    NSMutableString *myXmlStr = [[NSMutableString alloc] initWithData:xmlData encoding:NSUTF8StringEncoding];
    NSRange range = [myXmlStr rangeOfString:@"\n"];
    [myXmlStr replaceCharactersInRange:range withString:@"[:newline:]"];
    NSData *newXmlData = [myXmlStr dataUsingEncoding:NSUTF8StringEncoding];
    

    Just replace [:newline:] with new line character whenever u like it :)