how to parse xml files from a downloaded url file in swift
0
0
Entering edit mode
12 months ago

I am attempting to parse an XML file from the NCBI website using swift. When the file is in my Xcode project I have the code to parse that. I also have the code to download the file into swift. I am having trouble that once it is downloaded how to do I call the file and parse it from there. Below is my code for parsing the file that is in my Xcode project.

import UIKit
import XMLCoder

struct GBSet: Decodable{
    let GBSeq: GBSeq

}

struct GBSeq: Decodable{
    let GBSeq_locus: String
    let GBSeq_length: String
    let GBSeq_strandedness: String
    let GBSeq_moltype: String
    let GBSeq_definition: String
    let GBSeq_topology: String
    let GBSeq_keywords: String
    let GBSeq_source: String
    let GBSeq_organism: String
    let GBSeq_taxonomy: String
    let GBSeq_sequence: String
}
class ViewController: UIViewController, XMLParserDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
 let filePath = Bundle.main.path(forResource: "sequence", ofType: "xml")
       let data = try! Data(contentsOf: URL(fileURLWithPath: filePath!))

       let gbSet = try! XMLDecoder().decode(GBSet.self, from: data)
        print(gbSet)
}
}

Below is my code for downloading the xml file via url.

class ViewController: UIViewController, XMLParserDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
let seqId = "AB003468"
                let urlString = "https://www.ncbi.nlm.nih.gov/sviewer/viewer.cgi?tool=portal&save=file&log$=seqview&db=nuccore&report=gbc_xml&id=\(seqId)&conwithfeat=on&withparts=on&hide-cdd=on"
                let url = URL(string: urlString)!

                URLSession.shared.dataTask(with: url) { (data, response, error) in
                    if let error = error {
                        print(error.localizedDescription)
                        return
                    }

                    guard let data = data else {
                        print("invalid data!")
                        return
                    }

                    print(String(data: data, encoding: .utf8)!)
                }
                .resume()

How can I connect the two and download the file and then parse the file?

xcode swift XML Parse • 651 views
ADD COMMENT

Login before adding your answer.

Traffic: 1400 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6