都9102年了,如果遇到发送数据还需要用xml的时候,对于习惯了json的小伙伴实在是不太友好,所以写了简单的Dictionary转xml的方法。
使用extension对其扩展:
extension Dictionary {
//The outermost should be the root node, otherwise it violates the xml syntax specification
func xmlString() -> String {
let json = JSON(self)
var xml = ""
for key in json.dictionaryValue.keys {
let type = json[key].type
var value = ""
if type == .array {
let obj = json[key].arrayObject
value = arrayToXmlString(key, obj ?? [Any]())
} else if type == .dictionary {
let obj = json[key].dictionaryObject
value = obj?.xmlString() ?? ""
} else {
value = json[key].stringValue
}
if type == .array {
xml.append(value)
} else {
xml.append("<\(key)>\(value)</\(key)>")
}
}
return xml
}
private func arrayToXmlString(_ key: String, _ arr: [Any]) -> String {
let json = JSON(arr)
var xml = ""
for item in json.arrayValue {
let type = item.type
var value = ""
if type == .dictionary {//xml can't nested array with array
let obj = item.dictionaryObject
value = obj?.xmlString() ?? ""
} else {
value = json[key].stringValue
}
xml.append("<\(key)>\(value)</\(key)>")
}
return xml
}
}
1.xml的特点是每个node节点可以有属性attribute的,在发送数据的时候一般不对它进行编辑,所以我也没有在字典里面设计属性的规则
2.xml是不可能数组包裹数组的
3.xml的根节点必定是字典类型
扩展上面的方法的时候请考虑xml的其他特性和上面描述的3点,扩展基于递归处理字典、数组的原则生成简单的不带有
let desc = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>"
描述作为开头的xml字符串,下面是生成效果:
Dictionary:
▿ 1 element
▿ 0 : 2 elements
- key : "DSXClient"
▿ value : 1 element
▿ 0 : 2 elements
- key : "HeartBeat"
▿ value : 7 elements
▿ 0 : 2 elements
- key : "deviceType"
- value : "3"
▿ 1 : 2 elements
- key : "port"
- value : "7777"
▿ 2 : 2 elements
- key : "status"
- value : "0"
▿ 3 : 2 elements
- key : "login_id"
- value : "100123456"
▿ 4 : 2 elements
- key : "deviceNumber"
- value : "3VV8-L400-BI40-0"
▿ 5 : 2 elements
- key : "deviceId"
- value : "20160"
▿ 6 : 2 elements
- key : "host"
- value : "192.168.0.112"
XML:
<DSXClient>
<HeartBeat>
<status>0</status>
<deviceNumber>3VV8-L400-BI40-0</deviceNumber>
<port>7777</port>
<login_id>100123456</login_id>
<host>192.168.0.112</host>
<deviceType>3</deviceType>
<deviceId>20160</deviceId>
</HeartBeat>
</DSXClient>
使用时就可以很方便的编辑Dictionary转换xml
假设config是一个[String: Any]类型的字典
config[RequestModule.client] = ["AlertUpload": [
"deviceId":"20194", "deviceType":"3", "host":"192.168.0.199", "port":"7777", "alert_info":[
"createdAt":"2018-01-01 11:32:32",
"name":"test",
"type":"1",
"lockSn":"8U6K-MD00-BI40-0",
"mode":"1"
], "login_id":"100123456", "deviceNumber":"3VV8-L400-BI40-0"
]]