Since we are unable to use the NSXMLNode
, NSXMLDocument
, and NSXMLElement
classes in iOS projects, we generally need to manually build the XML string or 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 { xmlString += "<\(DocTags.BOOK_TAG) \(DocTags.NAME_TAG)=\"\(book.name)\">" xmlString += getElementString(DocTags.AUTHOR_TAG, elementValue: book.author) xmlString += getElementString(DocTags.CATEGORY_TAG, elementValue: book.category) xmlString += getElementString(DocTags.DESCRIPTION_TAG, elementValue: book.description) xmlString += getElementString(DocTags.PUBLISHER_TAG, elementValue: book.publisher) xmlString += "<\\\(DocTags.BOOK_TAG)>" } xmlString += "<\\\(DocTags.BOOKS_TAG)>" } return xmlString } func getElementString(elementName: String, elementValue: String) ->String { return "<\(elementName)>\"\(elementValue)\"<\\\(elementName)>" }
Since the
books
parameter is defined as optional, we begin the buildXMLString()
function by verifying it is not null with the if let myBooks = books
line. If it is null, the function will return an empty string; otherwise, we begin building the XML document.
In this class, we simply create strings that represent the XML tags and append them to the xmlString
variable. The xmlString
variable will contain the XML document at the end of the function.
The getElementString()
function creates a string that contains the start tag for the element, followed by the value of the element and the end tag for the element. This function is used to add most of the XML elements in this example.
As we can see, without an intimate knowledge of the syntax of XML documents, it would be virtually impossible to build complex documents with this method. We also need to be very careful to not to forget the closing tags at the end of an element.