Swift中XML解析的基本概念

问题描述 投票:0回答:1
I am brand new to parsing and cannot find any tutorial that isn't outdated and doesn't raise more questions. I have a simple xml file url I am trying to parse. The xml is very simple:   

**//create custom delegates to parse the data**
    @objc protocol ParserDelegate{
        @objc optional func parsingFinished (object: AnyObject?, withTag: NSInteger)
        @objc optional func parsingError (error: NSString?, withTag: NSInteger)
}
class BaseBusinessLayer: NSObject {
let NoInternet : NSString = "There seems to be some data connectivity issue with your network. Please check connection and try again."

        //declare callback variable
        var callBack : AnyObject!

        //Function to check Intenet
        func checkForInternet () {

            if callBack!.responds(to: Selector (("parsingError:withTag:")) ) {

                callBack!.parsingError!(error: NoInternet, withTag: NSInteger(0))
            }
            return
        }

}
**//Then create business layer class where we can create all parsing methods**

    class BusinessLayer: BaseBusinessLayer,ParserDelegate {

        //Here we define parsing method for News
        func GetNews()
        {
            let parser:NewsParser = NewsParser()
            parser.callBack = self.callBack;
            parser.beginParsing()
        }

}
**Then BO class where we can define all variables for parsing the data**

    class NewsBO: NSObject {

        var title = ""
        var link = ""
        var discription = ""
        var pubDate = ""

    }
**Now we call the methods from viewController**
    class ViewController: UIViewController {

        override func viewDidLoad() {
            super.viewDidLoad()
            callService()
        }
        func callService()  {

            let layer : BusinessLayer = BusinessLayer()
            layer.callBack = self
            layer.GetNews()
        }
        func parsingFinished(arr: NSMutableArray, withTag: NSInteger)
        {
            DispatchQueue.main.async{
                if withTag == 500
                {

                }
            }
        }
}
Thank you so much Rob. This helps immensely for people like me who are brand new and trying 

了解如何使用Swift进行解析。首先,编写所有代码以解析数据。在这里,我们试图解析XML解析过程,可帮助初学者以快速的语言解析数据。没有尝试任何复杂的代码。将XML数据解析为Swift对象的过程非常简单格式。

xml-parsing swift5
1个回答
0
投票

下一个用于解析数据的解析器类,这里我们定义了解析器的所有委托类NewsParser:NSObject,XMLParserDelegate {var callBack:AnyObject!var arrData = NSMutableArray()var parser = XMLParser()var posts = NSMutableArray()var元素= NSMutableDictionary()var element = NSString()var currentValue = NSMutableString()var currentObject = NewsBO()//自定义方法来调用解析func beginParsing(){帖子= []let aStr = String(格式:“ http://images.apple.com/main/rss/hotnews/hotnews.rss”)

            parser = XMLParser(contentsOf:(NSURL(string:aStr))! as URL)!
            parser.delegate = self
            parser.parse()

        }
        //XML delegate method distart element where we can create a memory for object
        func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String])
        {
            if (elementName as NSString).isEqual(to: "item")
            {
                currentObject = NewsBO()
            }
        }

        //XML delegate method didEndElemnt for maping/parsing the data into object format
        func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, 
        qualifiedName qName: String?)
        {
            if (elementName == "title") {
                currentObject.title = element as String
            }
            else if (elementName == "link") {
                currentObject.link = element as String
            }
            else if (elementName == "description") {
                currentObject.discription = element as String
            }
            else if (elementName == "pubDate") {
                currentObject.pubDate = element as String
            }
            else if (elementName == "item") {
                  arrData.addObjects(from: [currentObject])
            }

        }
        //Found character delegate is capturing tag values 

        func parser(_ parser: XMLParser, foundCharacters string: String)
        {
            element = string as NSString
        }

        //In this delegate method we can call callback mehod

        func parserDidEndDocument(_ parser: XMLParser) {

            if (self.callBack != nil && self.callBack is ViewController)
            {
                let vc: ViewController = self.callBack as! ViewController
                vc.parsingFinished(arr: arrData, withTag: 500)
            }

        }          
}
© www.soinside.com 2019 - 2024. All rights reserved.