2

I have an XML (in String format), I want to get individual values from it to string variables using Swift 4.

My data as given below:

let myString ="Adasdnajinasdshabjdbaiusd" //Encrypted Text(Sample)
let MyResult = self.TestObj.decryptData(myString); //Method for Encryption
print(MyResult) // Result in String Format

The output of MyResult is here:

<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><userDetails><status>success</status><name>Ashique</name><role>admin</role></userDetails>
.

This is in String format. So How can I get these values like Name and Role in to string variables in Swift 4?

Thanks in Advance!

4
  • Convert it to Json and parse it Commented May 14, 2018 at 10:09
  • You can use SwiftyXMLParser to Convert XML into String. For example : let xml = XML.parse(response.data!), let name = xml["name"] Commented May 14, 2018 at 10:10
  • I didn't find any suitable methods for it!, Do you have any links to share ? That would be helpful. Commented May 14, 2018 at 10:13
  • @Osman Thanks .. That worked... I'll update the answer...Thanks a lot..! :) Commented May 14, 2018 at 10:46

6 Answers 6

3

Using XMLParser with:

let parser = XMLParser.init(data: myString.data(using: .utf8))
parser.delegate = self
parser.parse()

inherits your class from XMLParseDelagate and implement this:

func parser(parse, element, namespace, name, attributes) {
 // check for your element and get attributes.
 // ..
}

More here

Sign up to request clarification or add additional context in comments.

1 Comment

That too will work... Thanks .. I used SwiftyXMLParser :)
2

You have multiple solutions.

  • Use XMLParser and XMLParserDelegate then the function parser
  • Use a library like SwiftyXMLParser

Comments

1

Using SwiftyXMLParser it worked.. here is the pod :

pod "SwiftyXMLParser", :git =>'https://github.com/yahoojapan/SwiftyXMLParser.git'

import SwiftyXMLParser
myString = <userDetails><status>success</status><name>Ashique</name></userDetails>


let xml1 = try! XML.parse(MyString!)                       
// access xml element
var element1 = xml1["userDetails"]["status"]; // Will Provide result -> success
var element2 = xml1["userDetails"]["name"] // will provide result -> Ashique

Comments

0
class ViewController: UIViewController , XMLParserDelegate , URLSessionDelegate {

    var parser:XMLParser?
    var foundChars: String = ""
    var personsStr: String = ""
    var currentElementName: NSString = ""
    var elementValue: String?

    override func viewDidLoad() {
        super.viewDidLoad()

         getPaticularInviteDetails(inviteId:"781")
    }

    func getPaticularInviteDetails(inviteId:String) {

            let soapMessage = "your_soap_request"
            let urlString = "your_soap_url"
            let url = NSURL(string: urlString)
            let theRequest = NSMutableURLRequest(url: url! as URL)
            let msgLength = soapMessage.characters.count
            theRequest.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
            theRequest.addValue(String(msgLength), forHTTPHeaderField: "Content-Length")
            theRequest.httpMethod = "POST"
            theRequest.httpBody = soapMessage.data(using: String.Encoding.utf8, allowLossyConversion: false)

            let session = URLSession.shared
            let task = session.dataTask(with: theRequest as URLRequest, completionHandler: { data, response, error -> Void in

            if error != nil {

                return
            }

            if let dat = data {

                let response = NSString(data: dat, encoding: String.Encoding.utf8.rawValue)
                print("XML Response ",    response!)

                let xmlParser = XMLParser(data: dat)
                xmlParser.delegate = self
                xmlParser.parse()
                xmlParser.shouldResolveExternalEntities = true
            }

            else {


            }
         })

        task.resume()
    }

    func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {

        currentElementName = elementName as NSString

        if elementName == "userDetails"//(your value) {

            print("It is coming")
            elementValue = String()
        }
    }

    func parser(_ parser: XMLParser, foundCharacters string: String) {

        particularInviteDetails(string: string)
    }

    func particularInviteDetails(string: String) {

            if elementValue != nil {

                elementValue! += string
            }
            let data: Data? = elementValue?.data(using: String.Encoding.utf8)

            do {

                let json = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:Any] ?? [:]
                print("\n json in Found Chara:",json)

                if json != nil {

                    let data = json?.object(forKey: "Data") as? String ?? ""
                    convertToDictionary(text: data)
                }

                else {

                }
            }
            catch {

            }
      }

    func convertToDictionary(text: String)  {

        if let data = text.data(using: .utf8) {

            do {

                let dict = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String:Any] ?? [:]
                let getData = dict?.value(forKey: "name") as? String ?? ""
                print("Result: ",getData)
            }
            catch {
                print(error.localizedDescription)
            }
        }
    }
}

Comments

0

If you don't mind using an external library, you can try XMLMapper.

You can use the following model:

class UserDetails: XMLMappable {
    var nodeName: String!

    var status: String?
    var name: String?
    var role: String?

    required init(map: XMLMap) { }

    func mapping(map: XMLMap) {
        status <- map["status"]
        name <- map["name"]
        role <- map["role"]
    }
}

And map your XML string like:

let userDetails = XMLMapper<UserDetails>().map(XMLString: MyResult)

Hope this helps.

Comments

0

XML structure:

<Services>
    <Service>
        <ServiceCode>7711</ServiceCode>
        <ServiceType>FLIGHT</ServiceType>
        <Supplier>Hüseyin METİN</Supplier>
        <Name>7711 (V)</Name>
    </Service>
</Services>

Code:

//Model.swift
class Service {
    var ServiceCode: Int
    var ServiceType: String
}

//ViewController.swift
class MonitorViewController: UIViewController {

    private var services: [Service] = []
    private var foundedService: Service?
    private var activeElement: String?

    //...
}

extension MonitorViewController: XMLParserDelegate {

    func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {

        if elementName == "Service" { // your element name
            foundedService = Service(ServiceCode: 0, ServiceType: "")
        }

        activeElement = elementName
    }

    func parser(_ parser: XMLParser, foundCharacters string: String) {
        switch activeElement {
        case "ServiceCode": foundedService?.ServiceCode = Int(string) ?? 0
        case "ServiceType": foundedService?.ServiceType = string
        default: break
        }
    }

    func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
        if elementName == "Service" { // your element name
            services.append(foundedService!)
            foundedService = nil
        }
    }

    func parserDidEndDocument(_ parser: XMLParser) {
        servicesTableView.reloadData()
    }
}

Comments

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.