3

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”}]"
2
  • Use xml parser to parse the xml you got. There is support for xml parsing in iOS and Swift: developer.apple.com/documentation/foundation/xmlparser Commented Jun 22, 2017 at 9:40
  • @firstinq can you elaborate with a code? i'm a bit new to swift. Commented Jun 22, 2017 at 9:44

1 Answer 1

1

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 = ""
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I got it, Thanks :)
This doesn't answer the question (XML -> JSON).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.