Anupam Mishra Anupam Mishra - 1 year ago 149
iOS Question

How to create a literal XML string with swift

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

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

for this i had objective-C code -

NSString *post = @"";
post = [NSString stringWithFormat:
@"<userDetail id=\'%@\'>xxxxx</userDetail>"
@"<trackInfo type=\"%@\" type_id=\"%@\" attending=\"%@\" event_date=\"%@\"/>"
, 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)\"/>" +

Result in Swift -

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

any help will be appreciated.

Answer Source

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.


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)


    <userDetail id='...'>xxxxx</userDetail>  
    <trackInfo type="..." type_id="..." attending="..." event_date="..."/>  
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download