首页 > 解决方案 > 如何在 Swift 中解析附加的 XML 并从中获取所有帐户信息

问题描述

我是 Swift 新手,发现很难用 Swift 语言解析链接的 XML。我尝试过使用 SWXMLHash pod 库,但对我没有帮助。我想从 XML 中提取帐户节点信息并将其存储在一个结构中。

XML

标签: swiftxml

解决方案


Since you don't mind using a third party library, you can try XMLMapper (similar to ObjectMapper but for XML)

Use the following model classes:

class GNCv2: XMLMappable {
    var nodeName: String!

    var gncAccounts: [GNCAccount]?

    required init?(map: XMLMap) {}

    func mapping(map: XMLMap) {
        gncAccounts <- map["gnc:book.gnc:account"]
    }
}

class GNCAccount: XMLMappable {
    var nodeName: String!

    var name: String?
    var id: AccountID?
    var type: String?
    var commoditySpace: String?
    var commodityID: String?
    var commoditySCU: Int?
    var description: String?
    var slots: AccountSlot?
    var parent: AccountID?

    required init(map: XMLMap) {}

    func mapping(map: XMLMap) {
        name <- map["act:name"]
        id <- map["act:id"]
        type <- map["act:type"]
        commoditySpace <- map["act:commodity.cmdty:space"]
        commodityID <- map["act:commodity.cmdty:id"]
        commoditySCU <- map["act:commodity-scu"]
        description <- map["act:description"]
        slots <- map["act:slots.slot"]
        parent <- map["act:parent"]
    }
}

class AccountID: XMLMappable {
    var nodeName: String!

    var type: String?
    var value: String?

    required init(map: XMLMap) {}

    func mapping(map: XMLMap) {
        type <- map.attributes["type"]
        value <- map.innerText
    }
}

class AccountSlot: XMLMappable {
    var nodeName: String!

    var key: String?
    var value: AccountSlotValue?

    required init(map: XMLMap) {}

    func mapping(map: XMLMap) {
        key <- map["slot:key"]
        value <- map["slot:value"]
    }
}

class AccountSlotValue: XMLMappable {
    var nodeName: String!

    var type: String?
    var value: Bool?

    required init(map: XMLMap) {}

    func mapping(map: XMLMap) {
        type <- map.attributes["type"]
        value <- map.innerText
    }
}

And map your XML using init(XMLString:) function of the root object class (in this case GNCv2) like:

let gncv2 = GNCv2(XMLString: xmlString)

You can achieve the exact same thing by using the map(XMLString:) function of the XMLMapper like:

let gncv2 = XMLMapper<GNCv2>().map(XMLString: xmlString)

Hope this helps.


推荐阅读