Wednesday, April 17, 2024
HomeiOS Developmentios - XML Parsing getting string inside brakets

ios – XML Parsing getting string inside brakets


Here’s a pattern of the XML knowledge I’m attempting to parse. Im having hassle determining the way to parse the info contained in the “” that’s nested inside the brackets i.e <one thing=”The right way to get this string”>. right here for instance id need to get “The right way to get this string”. I’m able to get the Knowledge if its in between the opening and shutting carrots I Bought this.

<METAR>
   <sky_condition sky_cover="OVC" cloud_base_ft_agl="2100"/> <---- get the OVC from sky_cover
   <flight_category>IFR</flight_category>
   <metar_type>METAR</metar_type>
</METAR>

Right here is my XML Parser Code & Delegate features

import Basis

class FeedParser: NSObject, XMLParserDelegate {
    non-public var airportItems: [FlightCategory] = [] // monitor parsing
    non-public var currentAirportElement: String = "" // monitor present merchandise being parsed
    non-public var parserCompletiongHandler: (([FlightCategory]) -> Void)? // deal with completion of parsing
    
    non-public var currentAirportFlightCategory: String = "" {
        didSet {
            // trim whitespace
            currentAirportFlightCategory = currentAirportFlightCategory.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
        }
    }
    
    non-public var currenAirportSkyCondition: String = "" {
        didSet {
            currenAirportSkyCondition = currenAirportSkyCondition.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
        }
    }
    
    // MARK: - URL Request
    
    // Hnadle Parsing feed
    func parseFeed(url: String, completionHandler: (([FlightCategory]) -> Void)?) {
        self.parserCompletiongHandler = completionHandler
        
        // URL Session Reques
        let request = URLRequest(url: URL(string: url)!)
        let session = URLSession.shared
        
        let job = session.dataTask(with: request) { knowledge, response, error in
            
            // if no knowledge
            guard let knowledge = knowledge else {
                if let error = error {
                    print(error.localizedDescription)
                }
                
                return
            }
            
            // if knowledge
            // parse xml knowledge
            let parser = XMLParser(knowledge: knowledge)
            parser.delegate = self
            parser.parse()
        }
        
        job.resume()
    }
    
    // MARK: - XML Parser Delegate
    func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
        // monitor present merchandise
        currentAirportElement = elementName
        if currentAirportElement == "METAR" { // it's there
            // currentAirportElement = ""
            
            currentAirportFlightCategory = ""
            currenAirportSkyCondition = ""
        }
    }
    
    // As soon as Parser get values of component Handler
    func parser(_ parser: XMLParser, foundCharacters string: String) {
        change currentAirportElement {
        case "flight_category": currentAirportFlightCategory += string
                
        default: break
        }
    }
    
    // As soon as Parser at Finish of component Handler
    func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
        if elementName == "METAR" { // "flight_category"
            let airportItems = FlightCategory(flight_category: currentAirportFlightCategory, sky_condition: currenAirportSkyCondition)
            self.airportItems.append(airportItems)
        }
    }
    
    // Name Completion Handler upon ending Parsing
    func parserDidEndDocument(_ parser: XMLParser) {
        parserCompletiongHandler?(airportItems)
    }
    
    // Deal with Parsing Errors
    func parser(_ parser: XMLParser, parseErrorOccurred parseError: any Error) {
        print(parseError.localizedDescription)
    }
}

And right here is how I’m loading the XML

non-public func loadXMLData() async {
        print("hmmmmm")
        let acwXMLURL = "https://aviationweather.gov/api/knowledge/dataserver?requestType=retrieve&dataSource=metars&stationString=KVNY&startTime=2024-03-10T21percent3A44percent3A22Z&format=xml&mostRecent=true"
        
        // parser feeder
        let feeder = FeedParser()
        feeder.parseFeed(url: acwXMLURL) { knowledge in
            self.detaileHomeAirportXML = knowledge
        }
    }
    
    non-public func handleXMLData() async {
        detaileHomeAirportXML?.forEach { merchandise in
            currentFltCat = merchandise.flight_category
            mannequin.airportFltCat = merchandise.flight_category
            print("XML knowledge dealt with: (currentFltCat)")
            
            if currentFltCat == "VFR" {
                shade = Shade(.inexperienced)
            } else if currentFltCat == "MVFR" {
                shade = Shade(.blue)
            } else if currentFltCat == "IFR" {
                shade = Shade(.purple)
            } else if currentFltCat == "LIFR" {
                shade = Shade(purple: 208 / 255, inexperienced: 45 / 255, blue: 208 / 255)
            }
        }
    }



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments