Reputation: 506
i have to extract and parse json from a text file, i know how to parse json but i'm just unable to extract it correctly from xml format. this is my xml which contains json.
<Data>
<Persons>[{"ID":"2","Name":"Catagory 1"},{"ID":"3","Name":"Catagory 2”</Persons>
<class>[{"ID":"3","Name":"WEAVING”}]</class>
</Data>
what i want is to get json sepratly with its tags, like for example.
"Persons":"[{"ID":"2","Name":"Catagory 1"},{"ID":"3","Name":"Catagory 2”}]"
Upvotes: 3
Views: 2439
Reputation: 782
Please find the sample code for parsing xml below:
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 = ""
}
}
Upvotes: 1