Book Image

Mastering Swift

By : Jon Hoffman
Book Image

Mastering Swift

By: Jon Hoffman

Overview of this book

Table of Contents (22 chapters)
Mastering Swift
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

XML and manually building XML documents


Since we are unable to use the NSXMLNode, NSXMLDocument, and NSXMLElement classes in iOS projects we generally need to manually build the XML string if we do not want to use third-party libraries. This method is error prone and it requires us to have a very good knowledge of how XML documents are built, but, if we are careful, we can create simple XML documents this way.

Let's see how to manually create an XML document. For this, we will create a function named builXMLString(), which takes an array of Book objects as its only parameter. We will also create a helper class named getElementString() that will create a string representation of an XML element. The getElementString() function will accept two elements, the element name and value. Let's have a look at the following code:

func buildXMLString(books: [Book]?) -> String {
  var xmlString = ""
  if let myBooks = books {
    xmlString = "<\(DocTags.BOOKS_TAG)>"
    for book in myBooks {
 ...