xmlswiftwebviewswift3xml-parsing

How do you show web view with XML parsed variable in Swift 3?


I'm pretty stuck in showing XML parsed data to web view.

import UIKit
import Fuzi

class ViewController: UIViewController {

@IBOutlet weak var webView: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    let myURLString = "https://www.naver.com"
    var myHTMLString = ""
    guard let myURL = URL(string: myURLString) else {
        print("Error: \(myURLString) doesn't seem to be a valid URL")
        return
    }

    do {
        myHTMLString = try String(contentsOf: myURL, encoding: .ascii)
    } catch let error {
        print("Error: \(error)")
    }

    do {
        let doc = try! HTMLDocument(string: myHTMLString, encoding: String.Encoding.utf8)

        // XPath queries
        if let firstDiv = doc.firstChild(xpath: "//*[@id='PM_ID_ct']/div[@class='container']") {
            print("44444")
            print(firstDiv)
            let body:String = firstDiv
            webView.loadHTMLString(firstDiv as String, baseURL: nil)
        }

    } catch let error{
        print(error)
    }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

The XML parsed well but when I put the xml variable into web view it makes an error. The error is:

Cannot convert value of type 'XMLElement' to specified type 'String'

Edit Here is one more try

When I changed

let body:String = firstDiv

to

let body:String = firstDiv.stringValue

It removes all the tags and attributes and remained only texts


Solution

  • stringValue only return strings. The correct method should be:

    let body: String = firstDiv.rawXML