快速解析给定元素名称的属性名称 [英] Swift parsing attribute name for given elementName

查看:18
本文介绍了快速解析给定元素名称的属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的网址的一部分

<cities>
  <country name="Абхазия">
    <city id="37188" region="27028" head="" type="3" country="Абхазия" part="" resort="" climate="">Новый Афон</city>
    <city id="37178" region="10282" head="" type="3" country="Абхазия" part="" resort="" climate="">Пицунда</city>
    <city id="37187" region="37187" head="" type="3" country="Абхазия" part="" resort="" climate="">Гудаута</city>
    <city id="37172" region="10280" head="" type="3" country="Абхазия" part="" resort="" climate="">Гагра</city>
    <city id="37189" region="10281" head="0" type="3" country="Абхазия" part="" resort="0" climate="">Сухум</city>
  </country>

用户输入城市名称,例如:"Пицунда" 我想获取它的 id.对于 "Пицунда" id 是 "10282".

User types the name of the city, for example: "Пицунда" and I want to get its id. For "Пицунда" id is "10282".

下面我发布了我的无效代码.

Below I've posted my not-working code.

var parser: NSXMLParser!
var city: String = String()
var ifDirOK = false
var ifCityNameOK = false


override func viewDidLoad() {
    super.viewDidLoad()

    let url: NSURL = NSURL(string: "https://pogoda.yandex.ru/static/cities.xml")!

    parser = NSXMLParser(contentsOfURL: url)
    parser.delegate = self
    parser.parse()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}



func parser(parser: NSXMLParser!, didStartElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!, attributes attributeDict: [NSObject : AnyObject]!) {
    //let cityID = attributeDict ["id"] as? NSString
    if (elementName == "city"){
        ifDirOK = true
    }
}

func parser(parser: NSXMLParser!, foundCharacters string: String!) {
    var data = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
    if (data == city){
        ifCityNameOK = true
    }
}

func parser(parser: NSXMLParser!, foundAttributeDeclarationWithName attributeName: String!, forElement elementName: String!, type: String!, defaultValue: String!) {
    if (ifDirOK && ifCityNameOK){
        println("(attributeName)")
    }
}

func parser(parser: NSXMLParser!, didEndElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!) {
}

毕竟,我想将 id 传递给另一个 URL 文件 (export.yandex.ru/weather-ng/forecasts/{id of the city}.xml) 并解析它.我是否需要创建另一个 Swift 类并以某种方式将其与第一个类连接起来?

After all, I want to pass id to another URL file (export.yandex.ru/weather-ng/forecasts/{id of the city}.xml) and parse it. Do I need to create another Swift class and somehow connect it with first one?

推荐答案

构建 [city:id] 的字典可能是您的解决方案.我已经根据 http 上关于 NSXMLParser 生命周期的文章实现了一个简单的解决方案://www.codeproject.com/Articles/248883/Objective-C-Fundamentals-NSXMLParser .

Building a dictionary of [city:id] can be a solution for you. I have implemented a simple solution based on the article about lifecycle of NSXMLParser at http://www.codeproject.com/Articles/248883/Objective-C-Fundamentals-NSXMLParser .

以下方法在元素启动时调用.您可以检索城市 id 属性并将其保存在实例级变量中,以便您可以在下一个方法中使用它.

Following method is called when when an element is starting. You can retrieve city id attribute and save it in an instance level variable so that you can use it in the next method.

func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [NSObject : AnyObject]) 

然后,当解析器看到开始和结束之间的任何内容时,就会调用 Follow 方法.

And then, Following method is called when the parser see anything between starting and ending.

func parser(parser: NSXMLParser!, foundCharacters string: String!) 

所以,您可以从这里获取城市名称.现在我们有了城市 id 和城市名称,可以将新项目添加到 [city:id] 字典中.

So, you can get the city name from here. Now we have city id and city name to add a new item into the [city:id] dictionary.

一旦你建立了字典,搜索就会非常简单.

Once you build the dictionary, searching would be very simple.

这是我的工作测试代码.

here is my working test code.

class ViewController: UIViewController ,NSXMLParserDelegate{
    var parser: NSXMLParser!
    var city: String = String()
    var ifDirOK = false
    var ifCityNameOK = false
     var element : String?
    var value: String=String()
    var dic = Dictionary<String,String>()
    var currentCityId:String?
    @IBOutlet weak var result: UILabel!

    @IBOutlet weak var search: UITextField! //search text

    @IBAction func ActionGoGetIt(sender: AnyObject) {

        self.result.text=dic[self.search.text]
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let url: NSURL = NSURL(string: "https://pogoda.yandex.ru/static/cities.xml")!

        parser = NSXMLParser(contentsOfURL: url)
        parser.delegate = self
        parser.parse()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }



    func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [NSObject : AnyObject]) {
        element = elementName

        if (element == "city"){
            ifDirOK = true
            let cityID = attributeDict ["id"] as? NSString
            self.currentCityId = cityID  as? String

        }
    }

    func parser(parser: NSXMLParser!, foundCharacters string: String!) {
        var data = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

        if (!data.isEmpty){
             if (element == "city"){
                    dic[data] = self.currentCityId as String?
            }

        }
    }

    func parser(parser: NSXMLParser, foundAttributeDeclarationWithName attributeName: String, forElement elementName: String, type: String?, defaultValue: String?) {
        if (ifDirOK && ifCityNameOK){
            println("(attributeName)")
        }
    }

    func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {

    }

}

这篇关于快速解析给定元素名称的属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆