Hugh
Hugh

Reputation: 1163

How to create a literal XML string with Objective-C?

I have long XML strings that I'm hard-coding into an iPhone project's unit tests.

It's pretty ugly having to escape all the quotes and line breaks -- for example:

NSString *xml = 
@"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<root>\
    <element name=\"foo\" />\
</root>";

It would be really nice to have a lower-friction way to do that.

I know Ruby has a great syntax for multiline literals... any suggestions for Objective-C?

Upvotes: 3

Views: 2246

Answers (1)

Rob Napier
Rob Napier

Reputation: 299355

ObjC also has multi-line literals, and single-quotes are legal in XML:

NSString *xml = 
@"<?xml version='1.0' encoding='UTF-8'?>"
 "<root>"
    "<element name='foo' />"
 "</root>";

Note that this doesn't embed newlines in the string, which is slightly different from your code.

Upvotes: 7

Related Questions