如何用Objective-C创建一个文本XML字符串?

时间:2022-12-07 22:28:06

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

我在iPhone项目的单元测试中硬编码了长长的XML字符串。

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?

我知道Ruby对于多行文字有很好的语法……objective - c的建议吗?

1 个解决方案

#1


7  

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

ObjC还有多行文字,单引号在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.

注意,这不会在字符串中嵌入新行,这与代码稍有不同。

#1


7  

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

ObjC还有多行文字,单引号在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.

注意,这不会在字符串中嵌入新行,这与代码稍有不同。