首页 > 解决方案 > 如何从xml解析字符串ios中删除或替换垃圾值或无效值&?

问题描述

无法从 xml 解析字符串中删除或&替换为。&我已经尝试了所有可能性,但我不知道哪里出了问题,也不知道如何用 & 删除或替换它。

let changeStr = getLocation.replacingOccurrences(of: "&", with: "&")这个电话没有取代。

//XML 获取位置

 let LocationMessage = "<?xml version='1.0' encoding='UTF-8'?><SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:ns1='http://tempuri.org/'><SOAP-ENV:Body><ns1:GetBROMCoordinateByLatLogRad><ns1:latitude>\(place.coordinate.latitude)</ns1:latitude><ns1:logitude>\(place.coordinate.longitude)</ns1:logitude><ns1:radius>500</ns1:radius></ns1:GetBROMCoordinateByLatLogRad></SOAP-ENV:Body></SOAP-ENV:Envelope>"

let LocationurlString = "http://xyz/POSCustAppWebService/API/POSApiService.svc"

let LocationmsgLength = String(LocationMessage.count)
let LocationUrl = NSURL(string: LocationurlString)!

var LocationRequest = URLRequest(url: LocationUrl as URL)
LocationRequest.addValue("text/xml", forHTTPHeaderField: "Content-Type")
LocationRequest.addValue("http://tempuri.org/IPOSApiService/GetBROMCoordinateByLatLogRad", forHTTPHeaderField: "Soapaction")
LocationRequest.addValue(LocationmsgLength, forHTTPHeaderField: "Content-Length")

LocationRequest.httpMethod = "POST"
LocationRequest.httpBody = LocationMessage.data(using: .utf8)

let Locationsession = URLSession.shared
let Locationtask = Locationsession.dataTask(with: LocationRequest as URLRequest) { (data, response, error) in
    guard let Locationresponse = data,
        error == nil else {
            print(error?.localizedDescription ?? "Response Error")
            return }

    print("Track Response: \(String(describing: response))")
    let Locationparser = XMLParser(data: Locationresponse)
    Locationparser.delegate = self
    Locationparser.parse()
}
Locationtask.resume()

//MARK:- XML 委托方法

func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
    currentParsingElement = elementName
    if elementName == "GetBROMCoordinateByLatLogRadResponse" {
        print("Started parsing...")
    }
}


func parser(_ parser: XMLParser, foundCharacters string: String) {
     let foundedChar = string.trimmingCharacters(in:NSCharacterSet.whitespacesAndNewlines)


    if (!foundedChar.isEmpty) {
        if currentParsingElement == "GetBROMCoordinateByLatLogRadResult" {
            getLocation = foundedChar
            print("Location is",getLocation)


          //  let encodedHost = unencodedHost.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

       /*     let encoded = "<strong> 4 &lt; 5 &amp; 3 &gt; 2 .</strong> Price: 12 &#x20ac;.  &#64; "
            let decoded = encoded.stringByDecodingHTMLEntities
            print(decoded)
            // <strong> 4 < 5 & 3 > 2 .</strong> Price: 12 €.  @
          */

            let jsonData = getLocation.data(using: .utf8)
            do{

                let jsonResponse = try JSONSerialization.jsonObject(with: jsonData!, options: .allowFragments)
                print("JSON Data is", jsonResponse) //Response result

                guard let jsonArray = jsonResponse as? [[String: Any]]
                    else {
                        return
                }

                print("JSON Array is", jsonArray)
                for outletFinderresult in jsonArray {

                    let outletFinderData = outletFinder()

        outletFinderData.BranchName = outletFinderresult["BranchName"] as! String
        print("Branch Name", outletFinderData.BranchName)
        outletFinderData.BranchType = outletFinderresult["BranchType"] as! String
        print("Branch Type", outletFinderData.BranchType)
        outletFinderData.BranchContactNo = outletFinderresult["BranchContactNo"] as! String
        print("Branch ContactNo", outletFinderData.BranchContactNo)

        let getOperatioHours = outletFinderresult["OperationHours"] as! String
        let removeN = String(getOperatioHours.filter { !"\n".contains($0) })
        outletFinderData.OperationHours = removeN
        print("Operation Hours", outletFinderData.OperationHours)

        var postString = outletFinderresult["BranchAddress1"] as! String
        postString += [","]
        postString += outletFinderresult["BranchAddress2"] as! String
        postString += [","]
        postString += outletFinderresult["BranchAddress3"] as! String
        postString += [","]
        postString += outletFinderresult["Postcode"] as! String
        postString += [","]
        postString += outletFinderresult["City"] as! String
        postString += [","]
        outletFinderData.Address = postString
        print("Address", outletFinderData.Address)

        outletFinderData.Latitude = (outletFinderresult["Latitude"] as! NSString).doubleValue
        print("Latitude", outletFinderData.Latitude)
        outletFinderData.Longitude = (outletFinderresult["Longitude"] as! NSString).doubleValue
        print("Longitude", outletFinderData.Longitude)

        self.trackOutletFinder.append(outletFinderData)

                }
                DispatchQueue.main.async {
                    self.outletCollectionView.reloadData()
                 //  elf.outletCollectionView.collectionViewLayout.invalidateLayout()

                }
            } catch let parsingError {
                print("Error", parsingError)
            }

        }
    }
}

func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
    if elementName == "GetBROMCoordinateByLatLogRadResponse" {
        print("Ended parsing...")
    }
}

标签: iosjsonswiftxml

解决方案


推荐阅读