views:

112

answers:

2

I need to indicated a 'new line' in a string in an XML file I'm loading.

If I hard code the string:

myTextView.text = [NSString stringWithString:@"Line1 \nLine2 \nLine3"];

It displays:

Line1
Line2
Line3

(as expected)

But if I put the exact string in my XML file:

<someNode string="Line1 \nLine2 \nLine3" />

And then load it into the UITableView it displays:

Line1 \nLine2 \nLine3

I've read somewhere that the '\n' character is processed at compile time, is this true? This would explain the behavior I'm seeing.

If this is the case, how else can I define a new line in my XML-loaded string and still have it properly processed in the UITextView? Is there another way to do this?

Thanks.

+1  A: 

You are right about \n being parsed at compile time.

NSString *b = [a stringByReplacingOccurrencesOfString:@"\\n" withString:@"\n"];

should do it!

BTW you may need to do similar replacements for \\, \", \t and the likes.

mvds
Brilliant! Thank you.
Nebs
A: 

Yes, the \n to newline conversion is done by your compiler.

In XML you can't really have a newline in an attribute value due to Attribute-Value Normalization. Any newline would just get converted to a space by a standards conformant parser. You can, however, have newlines in XML elements, so if you can change your XML to use elements rather than attributes for holding this text then you could just have literal newlines in your XML.

If you must use attributes, then you'll have to build your own representation of newlines on top of XML (as mvds suggests).

Laurence Gonsalves
Thanks for the info. I need to have this text as an attribute so mvds's answer is more appropriate.
Nebs