如何访问大子元素? [英] How to access grand child element?

查看:28
本文介绍了如何访问大子元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to learn XMLMapper, So I thought of using my W3 Schools XML example about books to try and map them my self.

所以我试图从一系列书籍中打印标题、作者.

So I'm trying to print title, author from an array of Books.

书籍.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 文件:

BooksXMLMappable.swift file:

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 中运行它:

Now I tried to run this in my ViewController's ViewDidLoad:

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

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

And I have successfully printed author for the first book, but I can't find a way to print author's of all the books without getting nil.

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

And if a book has multiple authors which one will be printed and how to print them all ?

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

Sorry if my question is too easy to solve, or a very basic one, but I'm trying to learn.

提前致谢.

推荐答案

for in loop for print author like this

used for in loop for print author like this

let storeObject = XMLMapper<BookStore>().map(XMLfile: "books.xml")
for book in storeObject.books {
      print(book.author)
}

这篇关于如何访问大子元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆