swift - 如何在 Swift 中解析附加的 XML 并从中获取所有帐户信息
问题描述
我是 Swift 新手,发现很难用 Swift 语言解析链接的 XML。我尝试过使用 SWXMLHash pod 库,但对我没有帮助。我想从 XML 中提取帐户节点信息并将其存储在一个结构中。
解决方案
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.
推荐阅读
- shell - 文件的最后一行未在 shell 脚本中读取
- android - Ionic3 将给定日期更改为所需格式
- android - 更改 android.support.design.widget 的 TextInputLayout 的 boxBackgroundColor
- reactjs - react + redux中的多次/批量删除
- postgresql - 我正在寻找一种将 int 切片或逗号分隔字符串传递到数据库/sql 'in' 查询中的方法
- javascript - WebRTC - 从服务器创建连接客户端-客户端
- cygwin - 符号链接 Cygwin vs. Msys2 vs. Win 10 (mklink)
- c++ - 使用放置在项目目录之外的 cmake 使用 ros 构建应用程序
- python - 基于公共字段pandas python添加列
- python - 熊猫重新采样到每月的特定工作日