Sunday, 5 April 2015

Working with XML in iOS


Working with XML in iOS


               Most of us have come across the problem in working with XML in making a server call. Among most of us have removed the complications by creating a string of tags inside which the relevant values substituted. This is a smart approach if our object has a static xml tree sturcture. But What if the xml tree structure is dynamic. To handle those situations, A simple and elegant way to construct an XML object in iOS can be possible using a library called XMLWriter by Thomas Rørvik Skjølberg.  Let's dive into the course...


                Although JSON objects are used in most of the server calls, XML objects still plays a vital role in server request/responses.  We are going to construct the following XML like tree structure, which is going to be our objective for this course.







For this tree structure we are going to have the customized objects as follows.
  1. Catalog
  2. Book
  3. DetailedInfo
So, in order to construct this tree structure the inner most object(from the above diagram) which is Detailed Info which has to be created as mentioned below.

DetailedInfo.h

DetailedInfo.m

Book.h

Book.m

Catalog.h

Catalog.m

Find the library here.

The skeleton of the xml snippet what we are going to construct would be look alike as the below image.


Let's get into to the coding part. Create a single page application in Xcode, Unzip the downloaded library from the above download link. There are two files named XMLWriter.h and XMLWriter.m add those two files inside the project under the target. The application's project navigator will be look like the below snapshot.

In the above snapshot the XMLWriter.h and XMLWriter.m are the library files will be used for XML conversion. The Catalog, Book and DetailedInfo files are created with the contents as mentioned the earlier snapshots. Our objective is to create an XML of content as follows.
<Catalog>
    <Book id="bk101">
         <Title>XML Developer's Guide</Title>
         <Author>Gambardella, Matthew</Title>
         <Price>250</Price>
         <Details>
              <Genre>Computer</Genre>
              <Published>2000-10-01</Published>
              <Description>An in-depth look at creating applications with XML.</Description>
          </Details>
    </Book>

    <Book id="bk102">
         <Title>Midnight Rain</Title>
         <Author>Ralls, Kim</Title>
         <Price>315</Price>
         <Details>
              <Genre>Fantasy</Genre>
              <Published>2000-12-16</Published>
              <Description>A former architect battles corporate zombies, an evil sorceress, and her own    childhood to become queen of the world.</Description>
          </Details>
    </Book>
</Catalog>



Open the ViewController.m and create the viewDidAppear method(C. Inside which write the following snippet.

No comments:

Post a Comment