About Kanna
Kanna is a lightweight XML/HTML parsing library in Swift, designed for easy navigation and manipulation of XML/HTML documents. It provides a simple and intuitive API for parsing, querying, and modifying XML/HTML content.
Features
- Efficient parsing and traversal of XML/HTML documents
- Support for XPath and CSS selectors for easy querying of XML/HTML elements
- Ability to modify XML/HTML content programmatically
- Built-in support for HTML5 parsing and entity decoding
- Lightweight and easy to integrate into your Swift projects
Installation
You can install Kanna using your preferred method:
- CocoaPods: Add the following line to your Podfile:
pod 'Kanna'
- Swift Package Manager: Add the following dependency to your Package.swift file:
.package(url: "https://github.com/tid-kijyun/Kanna.git", .upToNextMajor(from: "5.2.1"))
- Carthage: Add the following line to your Cartfile:
github "tid-kijyun/Kanna"
Usage
To start using Kanna, import the Kanna module in your Swift file:
// Import Kanna module
import Kanna
Then, you can parse an XML/HTML document using the try Kanna.XML
or try Kanna.HTML
methods, passing the document as a string:
// Parse an XML document
let xmlString = "<?xml version='1.0' encoding='UTF-8'?><root><item>Hello</item></root>"
if let xml = try? Kanna.XML(xml: xmlString, encoding: .utf8) {
// XML parsing successful
// Process or query the XML document here
}
// Parse an HTML document
let htmlString = "<!DOCTYPE html><html><head><title>Sample</title></head><body><h1>Hello, Kanna!</h1></body></html>"
if let html = try? Kanna.HTML(html: htmlString, encoding: .utf8) {
// HTML parsing successful
// Process or query the HTML document here
}
Once you have parsed the document, you can start navigating and manipulating its elements. Kanna provides various methods to select elements using XPath or CSS selectors. Here’s an example:
if let html = try? Kanna.HTML(html: htmlString, encoding: .utf8) {
// Query an element using XPath selector
if let title = html.at_xpath("//title") {
print(title.text) // Output: Sample
}
// Query elements using CSS selector
for link in html.css("a") {
print(link["href"]) // Output: URL of each link
}
}
To modify the content of the document, you can use the provided methods to add, delete, or update elements. Here’s an example:
if let html = try? Kanna.HTML(html: htmlString, encoding: .utf8) {
// Append a new element
let body = html.at_css("body")
body?.append(newElement: "p", text: "This is a new paragraph")
// Delete an element
if let title = html.at_css("title") {
title.removeFromParent()
}
// Update element text
if let h1 = html.at_css("h1") {
h1.text = "Hello, Kanna!"
}
// Output the modified HTML
print(html.toHTML)
}
Documentation & Resources
For comprehensive documentation on using Kanna, visit the official GitHub repository:
Contributing
If you encounter any issues or have suggestions for improvement, feel free to contribute to the Kanna project. Visit the GitHub repository for more information.