Search code examples
iosxmlnsdictionary

Converting NSDictionary to XML


I need to Post data in XML format. The server accepts a specific xml format. I don't want to write the xml by hand, what i want to do is create a NSMutableDictionary populate it and from NSMutableDictionary convert it XML.

I use this:

[NSPropertyListSerialization dataWithPropertyList:data format:NSPropertyListXMLFormat_v1_0 options:0

The sample return is this:

<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0">
<dict>
<key>email</key>
<string>[email protected]</string>
<key>invoice_date</key>
<string>2012-10-11T10:35:09Z</string>
<key>invoice_lines</key>
<array>
    <dict>
        <key>product_id</key>
        <integer>1021493</integer>
        <key>quantity</key>
        <real>1</real>
        <key>retail_price</key>
        <real>110</real>
    </dict>
</array>
<key>payments</key>
<array>
    <dict>
        <key>amount</key>
        <real>288.5</real>
    </dict>
    <dict>
        <key>payment_type_id</key>
        <integer>1</integer>
    </dict>
</array>

The above format is not readable from the server.

The server need an xml feed like this.

  <invoice>
      <invoice_date>2012-10-11T10:35:09Z</invoice_date>
      <email>[email protected]</email>
        <invoice_lines type="array">
         <invoice_line>
       <product_id>1021505</product_id>
       <quantity>1</quantity>
       <retail_price>45</retail_price>
     </invoice_line>
  </invoice_lines>
  <payments type="array">
    <payment>
      <amount>288.5</amount>
     </payment>
  </payments>

</invoice>

Is it possible to generate the above xml coming from a NSDictionary?

Thanks!


Solution

  • The short answer is: No, there is no built-in ability to do this in the Cocoa libraries.

    Because you're writing rather than parsing, and presumably dealing with a limited universe of possible tags, the code to output XML is actually not that complicated. It should just be a simple method in your Invoice object, something like:

    - (NSString*) postStringInXMLFormat
    {
        NSMutableString* returnValue = [[NSMutableString alloc] init];
        if([self email])
        {
            [returnValue appendString:@"<email>"];
            [returnValue appendString:[self email]];
            [returnValue appendString:@"</email>"];
        }
        if([self invoice_date])
        ...
    

    and so on. At the end return

    [NSString stringWithString:returnValue]
    

    There are plenty of third-party projects out there that try to generalize this process; several of them are listed in this answer:

    Xml serialization library for iPhone Apps

    But if all you're looking to do is create a single, stable format that your server side will recognize, and you don't have a ridiculous number of entities to convert, it's probably less work to roll your own.