Kanna (鉋)

Kanna (鉋) 是一个跨平台(macOS, iOS, tvOS, watchOS 和 Linux!)的 XML/HTML 解析器。

它的灵感来源于 Nokogiri (鋸)。

CI Platform Cocoapod Carthage compatible Swift Package Manager MIT License

ℹ️ 文档

特性

Swift 5 的安装

CocoaPods

将以下内容添加到您的 Podfile

use_frameworks!
pod 'Kanna', '~> 5.2.2'

Carthage

将以下内容添加到您的 Cartfile

github "tid-kijyun/Kanna" ~> 5.2.2

对于 Xcode 11.3 及更早版本,需要以下设置。

  1. 在项目设置中,将 $(SDKROOT)/usr/include/libxml2 添加到 "header search paths" 字段

Swift Package Manager

  1. 将 libxml2 安装到您的计算机
// macOS: For xcode 11.3 and earlier, the following settings are required.
$ brew install libxml2
$ brew link --force libxml2

// Linux(Ubuntu):
$ sudo apt-get install libxml2-dev
  1. 将以下内容添加到您的 Package.swift
// swift-tools-version:5.0
import PackageDescription

let package = Package(
    name: "YourProject",
    dependencies: [
        .package(url: "https://github.com/tid-kijyun/Kanna.git", from: "5.2.2"),
    ],
    targets: [
        .target(
            name: "YourTarget",
            dependencies: ["Kanna"]),
    ]
)
$ swift build

注意: 当出现构建错误时,请尝试运行以下命令

// Linux(Ubuntu)
$ sudo apt-get install pkg-config

手动安装

  1. 将这些文件添加到您的项目
    Kanna.swift
    CSS.swift
    libxmlHTMLDocument.swift
    libxmlHTMLNode.swift
    libxmlParserOption.swift
    模块
  2. 在目标设置中,将 $(SDKROOT)/usr/include/libxml2 添加到 Search Paths > Header Search Paths 字段
  3. 在目标设置中,将 $(SRCROOT)/Modules 添加到 Swift Compiler - Search Paths > Import Paths 字段

Swift 4 的安装

Swift 3 的安装

概要

import Kanna

let html = "<html>...</html>"

if let doc = try? HTML(html: html, encoding: .utf8) {
    print(doc.title)
    
    // Search for nodes by CSS
    for link in doc.css("a, link") {
        print(link.text)
        print(link["href"])
    }
    
    // Search for nodes by XPath
    for link in doc.xpath("//a | //link") {
        print(link.text)
        print(link["href"])
    }
}
let xml = "..."
if let doc = try? Kanna.XML(xml: xml, encoding: .utf8) {
    let namespaces = [
                    "o":  "urn:schemas-microsoft-com:office:office",
                    "ss": "urn:schemas-microsoft-com:office:spreadsheet"
                ]
    if let author = doc.at_xpath("//o:Author", namespaces: namespaces) {
        print(author.text)
    }
}

捐赠

如果您喜欢 Kanna,请通过 GitHub Sponsors 或 PayPal 进行捐赠。
这将用于改进和维护该库。

许可证

MIT 许可证。 有关更多信息,请参见 LICENSE 文件。