2

我正在尝试学习 XMLMapper,所以我想使用我的 W3 Schools XML 示例来尝试自己映射它们。

所以我正在尝试从一系列书籍中打印标题,作者。

书籍.XML

<?xml version="1.0" encoding="utf-8"?>
<bookstore>
    <book>
        <title>Everyday Italian</title>
        <author>Giada De Laurentiis</author>
        <year>2005</year>
        <price>30.00</price>
    </book>
    <book>
        <title>Harry Potter</title>
        <author>J K. Rowling</author>
        <year>2005</year>
        <price>29.99</price>
    </book>
    <book>
        <title>XQuery Kick Start</title>
        <author>James McGovern</author>
        <author>Per Bothner</author>
        <author>Kurt Cagle</author>
        <author>James Linn</author>
        <author>Vaidyanathan Nagarajan</author>
        <year>2003</year>
        <price>49.99</price>
    </book>
    <book>
        <title>Learning XML</title>
        <author>Erik T. Ray</author>
        <year>2003</year>
        <price>39.95</price>
    </book>
</bookstore>

BooksXMLMappable.swift 文件:

import Foundation
import XMLMapper

class BookStore: XMLMappable {
    required init?(map: XMLMap) {
        //Empty
    }

    var nodeName: String!

    var books: [Book]?

    func mapping(map: XMLMap) {
        books <- map["book"]

    }

}

class Book: XMLMappable {
    required init?(map: XMLMap) {
        //Empty
    }

    var nodeName: String!

    var title: String!
    var author: String?
    var year: Int?
    var price: Double?


    func mapping(map: XMLMap) {
        //category <- map.attributes["category"]
        title <- map["title"]
        author <- map["author"]
        year <- map["year"]
        price <- map["price"]
    }

}

现在我尝试在我的 ViewController 的 ViewDidLoad 中运行它:

let storeObject = XMLMapper<BookStore>().map(XMLfile: "books.xml")
        print(storeObject?.books?.first?.author ?? "nil")

我已经成功地打印了第一本书的作者,但是我找不到一种方法来打印所有书籍的作者而不得到零。

如果一本书有多个作者,将打印哪一个以及如何全部打印?

对不起,如果我的问题太容易解决,或者是一个非常基本的问题,但我正在努力学习。

提前致谢。

4

2 回答 2

2

You are getting a nil in author value, in the third book, because there are more than one authors.

Since version 1.4.4 of XMLMapper you can map those cases using an Array.

In your case, specifically, you can map the author tag using an Array of String like:

class Book: XMLMappable {
    required init?(map: XMLMap) {
        //Empty
    }

    var nodeName: String!

    var title: String!
    var authors: [String]?
    var year: Int?
    var price: Double?


    func mapping(map: XMLMap) {
        //category <- map.attributes["category"]
        title <- map["title"]
        authors <- map["author"]
        year <- map["year"]
        price <- map["price"]
    }
}

Then you can access all the authors, looping the authors Array.

Hope this helps.

于 2018-10-31T11:11:23.170 回答
1

像这样用于打印作者的循环

let storeObject = XMLMapper<BookStore>().map(XMLfile: "books.xml")
for book in storeObject.books {
      print(book.author)
}
于 2018-10-30T05:56:26.460 回答