I have an XML file that has the following data:
<Book>
<title>Some Random Book</title>
<author>Someone Someone</author>
<book_type>
<FICT />
<REF />
</book_type>
</Book>
I’m trying to write a struct for it, but I’m not sure how to deal with the self-closing tags inside "book_type". Are those enums? Not all books will have a "book_type", and if they do, there could be more than one like in the example above.
Here’s what I have, not sure if this is correct:
struct Book {
var title: String?
var author: String?
var book_type: BookType?
}
enum BookType {
case fiction
case nonfiction
case reference
case autobiography
}
Thank you!
2
Answers
Each tag in XML can be seen as representing an object. In this case
Book
is a complex object with multiple attributes.title
andauthor
are simple objects and can be represented with an existing data type (String). From the example it looks likeBook
can have multiple book types, sobook_type
could be represented as an array. This could be an array of Strings or Enums, this is up to you and how these values would be used elsewhere in the code.In terms of the self-closing tags, I believe the tag name normally represents the name of attribute, not the value of the tag. A self-closing tag is analogous to an object with default values. In the case of having multiple values, it can be tricky to see the differentiation because you don’t give a name to items in a list.
The way I’d organise the XML data would be something like:
And the Swift model struct:
Hope this helps.
The problem you are having has nothing to do with parsing the XML. This is valid XML; parsing it is easy enough. The problem is that you need to come up with some way of representing the XML as an object. The way you do that is totally up to you; there are no magic rules. The thing to keep in mind is that not every XML topology is readily converted to a Swift object — and this is an example of such a topology.
If you know for a fact that the four book types you have listed in your BookType enum are the only ones that will ever be encountered, then it seems to me that Book’s
book_type
would most conveniently be a Set of BookType, since the order doesn’t matter and a given type either is or is not in the list (and if there is nobook_type
then the set can simply be empty):You’ll notice that I didn’t make anything Optional, since I assume that every book has a title and an author. But that is only an assumption; it is up to you to design these objects based on what you know to be the ways the XML can legally be structured.