Swift开发:创建XML文件,包含节点,属性值

Swift开发:创建XML文件,包含节点,属性值,第1张

概述---------------XmlWrite.swift----------------- //// XmlWrite.swift// CreateXmlFile//// Created by 黄涛 on 16/5/25.// Copyright © 2016年 黄涛. All rights reserved.//import UIKitclass XmlWrite

---------------XmlWrite.swift-----------------

////  XmlWrite.swift//  CreateXmlfile////  Created by 黄涛 on 16/5/25.//  copyright © 2016年 黄涛. All rights reserved.//import UIKitclass XmlWrite: NSObject {        fileprivate let xmlhead = "<?xml version='1.0' enCoding='UTF-8' standalone='yes' ?>"    fileprivate var dirPath = ""    fileprivate var filename = ""    fileprivate var filePath = ""    fileprivate var root = "";    init(dir: String,filename: String,root:String) {        super.init()        self.dirPath = dir        self.filename = filename        self.filePath = dirPath + self.filename        self.root = root;        items = [];    }        var items:[Item]?;         func saveXml() {                        let data = NSMutableData()//可变数据                        // xml 文件声明            data.append("\(xmlhead)\n<\(root)>\n".data(using: String.EnCoding.utf8,allowLossyConversion: true)!)                        // 遍历 item  第一层            for i in 0..<items!.count  {                                if items![i].attributes != nil {                                        // 获取item 属性string                    let itemStr:String? = ItemToString(items![i])                    // 添加item属性                    data.append("  \(itemStr!)\n".data(using: String.EnCoding.utf8,allowLossyConversion: true)!)                                    }                                // 当前item 的node集合                let nodes = items![i].nodes;                                for j in 0..<nodes!.count {                    //获取node 属性string                    let node = (nodes?[j])!;                    // 判断当前节点的子节点                    let isSub = node.subNode?.count > 0 ? true : false;                                        let nodeStr:String? = NodetoString(node,isSub: isSub);                    // print(nodeStr)                    // 添加node属性                    data.append("    \(nodeStr!)\n".data(using: String.EnCoding.utf8,allowLossyConversion: true)!)                                       if node.subNode?.count > 0                    {                        for k in 0..<node.subNode!.count                        {                            //获取node 属性string                            let snode = node.subNode?[k];                            let snodeStr:String? = NodetoString(snode!,isSub: false);                           // print(snodeStr)                            // 添加node属性                            data.append("      \(snodeStr!)\n".data(using: String.EnCoding.utf8,allowLossyConversion: true)!)                            data.write(tofile: filePath,atomically: true)                        }                      // 当前 子节点 结束                      data.append("    </\(node.name)>\n".data(using: String.EnCoding.utf8,allowLossyConversion: true)!)                    }                }                                // 当前 item 结束                data.append("  </\(items![i].name)>\n".data(using: String.EnCoding.utf8,allowLossyConversion: true)!)                data.write(tofile: filePath,atomically: true)            }                    // 当前 root 结束            data.append("</\(root)>\n".data(using: String.EnCoding.utf8,allowLossyConversion: true)!)                    //写入文件中            data.write(tofile: filePath,atomically: true)                    print(filePath)        }            func ItemToString(_ item:Item) ->String {            // 1 拼接 节点名称            let nodename = item.name            var nodeStr:String = nodename.elementStartTag() + " "                        if item.attributes?.count  == 0 {                return nodeStr;            }            // 2 拼接节点 属性            for (key,value) in (item.attributes)! {                nodeStr += "\(key)=\"\(value)\" "            }            nodeStr += ">"            return nodeStr        }            func NodetoString(_ node:Node,isSub:Bool) ->String {            // 1 拼接 节点名称            let nodename = node.name            var nodeStr:String = nodename.elementStartTag() + " "                        // 2 拼接节点 属性            for (key,value) in (node.attributes)! {                nodeStr += "\(key)=\"\(value)\" "            }                    if isSub {                nodeStr += ">"            }            else {                nodeStr += "/>"            }            return nodeStr        }    }        class Item {        init(name:String) {            self.name = name;            nodes = [];        }        var name:String = "";        var attributes:[String:String]?        var nodes:[Node]?;                func addNode(_ node:Node){            nodes?.append(node);        }            }        class Node {        init(name:String) {            self.name = name;            subNode = [];        }        init (){            subNode = [];        }        var ID = 0;        var name = ""        var attributes:[String:String]?        var subNode:[Node]?;                func addSubNode(_ node:Node){            subNode?.append(node);        }    }            extension String {                func elementStartTag() -> String {            return "<" + self        }                func elementEndAttributesTag() -> String {            return  self + ">"        }                func elementEndTag() -> String {            return "</" + self + ">"        }                }




-----------------代码调用---------------

dispatch_async(dispatch_get_main_queue()) { () ->VoID in

// 1 创建xml文件路径,名称

let xml =XmlWrite(dir: "/Users/huangtao/Desktop/",filename:"data.xml")

// 2 创建第一个节点数据

let item1:Item =Item(name: "Item1");

item1.attributes = ["A1":"1","A2":"2"]

for(var i=0;i<5;i++) {

let node =Node(name:"note-\(i)");

node.ID = i+1;

node.attributes = ["ID":"\(i)","name":"我的名称-\(i)"]

item1.addNode(node);

}

xml.items?.append(item1);

// 3 创建第二个节点数据

let item2:Item =Item(name: "Item2");

for(var i=0;i<10;i++) {

let node =Node(name:"note-\(i)");

node.ID = i+1;

node.attributes = ["ID":"\(i)","name":"N-\(i)","disp":"1","Appliance":"1","Icon":"ic_switch_4"]

item2.addNode(node);

}

xml.items?.append(item2);

// 4 保存文件

xml.saveXml()

}


----------------- 效果图 ---------------




解析xml见博客:

http://www.jb51.cc/article/p-xudpqbfh-bgc.html

总结

以上是内存溢出为你收集整理的Swift开发:创建XML文件,包含节点,属性值全部内容,希望文章能够帮你解决Swift开发:创建XML文件,包含节点,属性值所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1065077.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-26
下一篇 2022-05-26

发表评论

登录后才能评论

评论列表(0条)

保存