如何在Swift中从xml获取数据

时间:2019-05-09 05:57:40

标签: swift xml xml-parsing

我想从XML获得服务响应。我尝试了'SWXMLHash'  ,'SwiftyXMLParser'。

我需要这个值:Device is Registered

<?xml version="1.0" encoding="utf-8"?><soap:Envelope 
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body> 
<QR_GetDeviceCheckAndRegistrationResponse 
xmlns="http://www.bdmitech.com/m2b"> 
<QR_GetDeviceCheckAndRegistrationResult>Device is 
Registered</QR_GetDeviceCheckAndRegistrationResult> 
</QR_GetDeviceCheckAndRegistrationResponse></soap:Body> 
</soap:Envelope>

1 个答案:

答案 0 :(得分:0)

如果仅使用XMLParser,则要定义一个委托对象:

class ParserDelegate: NSObject, XMLParserDelegate {
    var currentValue: String?
    var registrationResult: String?

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

    func parser(_ parser: XMLParser, foundCharacters string: String) {
        currentValue? += string
    }

    func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
        if elementName == "QR_GetDeviceCheckAndRegistrationResult" {
            registrationResult = currentValue
            currentValue = nil
        }
    }

    func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
        print(parseError)
    }
}

然后您将解析:

let parser = XMLParser(data: data)
let parserDelegate = ParserDelegate()
parser.delegate = parserDelegate
guard 
    parser.parse(),
    let result = parserDelegate.registrationResult
else { return }
print(result)