Anupam Mishra Anupam Mishra - 5 months ago 35
iOS Question

How to create a literal XML string with swift

I wants to generate XML string something like this in swift -

<userTracking>
<userDetail id='1178085'>xxxx</userDetail>
<trackInfo type="xxxxx" type_id="xxxxxxx" attending="x" event_date="2016-07-01"/>
</userTracking>


for this i had objective-C code -

NSString *post = @"";
post = [NSString stringWithFormat:
@"<userTracking>"
@"<userDetail id=\'%@\'>xxxxx</userDetail>"
@"<trackInfo type=\"%@\" type_id=\"%@\" attending=\"%@\" event_date=\"%@\"/>"
@"</userTracking>"
, UserID,type, typeID, attending,event_date];


which is working great. Now i wants to generate same thing in swift & done following code but getting wrong XML formatted string -

swift Code -

var post = "";
post = "<userTracking>" +
"<userDetail id='\(UserID)\'>xxxxx</userDetail>" +
"<trackInfo type=\"\(type)\" type_id=\"\(typeID)\" attending=\"\(attending)\" event_date=\"\(event_date)\"/>" +
"</userTracking>";


Result in Swift -

<userTracking>
<userDetail id=\'xxxxx\'>xxxxx</userDetail>
<trackInfo type=\"xxxx\" type_id=\"xxx\" attending=\"4\" event_date=\"2016-07-01\"/>
</userTracking>


any help will be appreciated.

Answer

You can also use String(format:) in Swift.

Don't forget to escape all double quotes, and add newlines ("\n") and tabs ("\t") if needed.

Example:

let post = String(format: "<userTracking>\n\t<userDetail id=\'%@\'>xxxxx</userDetail>\n\t<trackInfo type=\"%@\" type_id=\"%@\" attending=\"%@\" event_date=\"%@\"/>\n</userTracking>", UserID, type, typeID, attending, event_date)

Gives:

<userTracking>  
    <userDetail id='...'>xxxxx</userDetail>  
    <trackInfo type="..." type_id="..." attending="..." event_date="..."/>  
</userTracking>
Comments