Skip to content

Instantly share code, notes, and snippets.

@stonezhl
Last active August 16, 2019 15:41
Show Gist options
  • Save stonezhl/854cfb7e5fb11b9008b92cbc65369281 to your computer and use it in GitHub Desktop.
Save stonezhl/854cfb7e5fb11b9008b92cbc65369281 to your computer and use it in GitHub Desktop.
OPFDocument Struct
import Kanna
struct OPFDocument {
let metadata: OPFMetadata
let manifest: OPFManifest
let spine: OPFSpine
// Other elements, like collection, guide, etc.
let document: XMLDocument
init?(url: URL) {
do {
// Get the OPF XMLDocument
document = try Kanna.XML(url: url, encoding: .utf8)
// Create namespace for the 'package' element
let opfNamespace = ["opf": "http://www.idpf.org/2007/opf"]
// Execute XPath query to fetch the 'package' element
guard let package = document.at_xpath("/opf:package", namespaces: opfNamespace) else { return nil }
// Parse the three main elements
// Will explain them later
guard let metadata = OPFMetadata(package: package) else { return nil }
guard let manifest = OPFManifest(package: package) else { return nil }
guard let spine = OPFSpine(package: package) else { return nil }
self.metadata = metadata
self.manifest = manifest
self.spine = spine
} catch {
print("Parsing the XML file at \(url) failed with error: \(error)")
return nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment