Swift解析给定elementName的属性名称

前端之家收集整理的这篇文章主要介绍了Swift解析给定elementName的属性名称前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是我网址的一部分
<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”.

下面我发布了我的工作代码.

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!,qualifiedName qName: String!) {
}

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

建立[city:id]字典可以为您提供解决方案.
我已经基于关于NSXMLParser生命周期的文章http://www.codeproject.com/Articles/248883/Objective-C-Fundamentals-NSXMLParser实现了一个简单的解决方案.

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

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

然后,当解析器在开始和结束之间看到任何内容调用Following方法.

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

所以,你可以从这里获得城市名称.
现在我们有城市ID和城市名称,以便在[city:id]字典中添加新项目.

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

这是我的工作测试代码.

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,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,qualifiedName qName: String?) {

    }

}
原文链接:https://www.f2er.com/swift/320089.html

猜你在找的Swift相关文章