2017-06-22 137 views
3

我必須從文本文件中提取和解析json,我知道如何解析json,但我無法從xml格式正確提取它。這是我的包含json的xml。從iOS的xml文本文件中提取Json Swift

<Data> 
<Persons>[{"ID":"2","Name":"Catagory 1"},{"ID":"3","Name":"Catagory 2」</Persons> 
<class>[{"ID":"3","Name":"WEAVING」}]</class> 
</Data> 

我想要的就是讓json獨立使用它的標籤,例如。

"Persons":"[{"ID":"2","Name":"Catagory 1"},{"ID":"3","Name":"Catagory 2」}]" 
+0

使用XML解析器來解析你得到了XML。支持iOS和Swift中的xml解析:https://developer.apple.com/documentation/foundation/xmlparser – firstinq

+0

@firstinq你可以用代碼來詳細說明嗎?我很快就有點新意了。 –

回答

1

請找到示例代碼如下解析XML:

import UIKit 
import Foundation 
class ViewController: UIViewController { 

    var parser:XMLParser? 
    var foundChars: String = "" 
    var personsStr: String = "" 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     parseXML() 
     // Do any additional setup after loading the view, typically from a nib. 
    } 

    func parseXML() { 
     let str: NSString = "<Data><Persons>[{\"ID\":\"2\",\"Name\":\"Catagory 1\"},{\"ID\":\"3\",\"Name\":\"Catagory 2\"}]</Persons><class>[{\"ID\":\"3\",\"Name\":\"WEAVING\"}]</class></Data>" 
     if let data = str.data(using: String.Encoding.utf8.rawValue) { 
      parser = XMLParser.init(data: data) 
      parser!.delegate = self 
      parser!.parse() 
     } 

    } 
} 
extension ViewController: XMLParserDelegate { 
    public func parserDidEndDocument(_ parser: XMLParser) { 
     debugPrint("Person str is:: " + self.personsStr) 
     //TODO: You have to build your json object from the PersonStr now 
    } 
    func parser(_ parser: XMLParser, foundCharacters string: String) { 
     self.foundChars = self.foundChars + string 
    } 
    func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { 
     debugPrint("end element::" + elementName) 
     if (elementName == "Persons") { 
      self.personsStr = self.foundChars 
     } 
     self.foundChars = "" 
    } 
} 
+0

我明白了,謝謝:) –

+0

這不會回答這個問題(XML - > JSON)。 – Koen