简体   繁体   中英

xml soap with swift (IOS 8)

I have an Asp.net web service (SOAP) and there are some methods (functions) I want to call one of the methods that I have it on my web service the pares the result (XML result)

Exactly what I need to now:

1- how to call my webservice (SOAP) 2- the return result like this

<string xmlns="http://tempuri.org/"><FirstName>test</FirstName><MI>A</MI> <LastName>testLast</LastName>

how can I pares it?

Thank you.

I wrote a pod for mapping XML to objects, called XMLMapper . (uses the same technique as the ObjectMapper )

Using the Requests subspec you can create a SOAPEnvelope like:

let soapMessage = SOAPMessage(soapAction: "ActionName", nameSpace: "ActionNameSpace")
let soapEnvelope = SOAPEnvelope(soapMessage: soapMessage)

And then send it with Alamofire:

Alamofire.request(url, method: .post, parameters: soapEnvelope.toXML(), encoding: XMLEncoding.soap(withAction: "ActionNameSpace#ActionName"))

Mapping the response XML requires you to implement XMLMappable protocol

For example you can map the following xml:

<Food>
    <name>Belgian Waffles</name>
    <price>5.95</price>
    <description>
        Two of our famous Belgian Waffles with plenty of real maple syrup
    </description>
    <calories>650</calories>
</Food>

With Food object:

class Food: XMLMappable {
    var nodeName: String!

    var name: String!
    var price: Float!
    var description: String?
    var calories: Int?

    required init(map: XMLMap) {

    }

    func mapping(map: XMLMap) {
        name <- map["name"]
        price <- map["price"]
        description <- map["description"]
        calories <- map["calories"]
    }
}

Using Alamofire and responseXMLObject(completionHandler:) function like:

Alamofire.request(url).responseXMLObject { (response: DataResponse<Food>) in
    let food = response.result.value
    print(food.toXMLString() ?? "nil")
}

Give it a try

I made this new simple and lightweight XML parser for iOS in Swift - AEXML

You can use it to read XML data like this:

let someValue = xmlDocument["element"]["child"]["anotherChild"].value

or you can use it to build XML string like this:

let document = AEXMLDocument()
let element = document.addChild("element")
element.addChild("child")
document.xmlString // returns XML string of the entire document structure

I hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM