一个用于处理 HTML、XML 和其他标记语言的 Swift 包,基于 libxml2。
本项目正在积极开发中,尚未准备好用于生产环境。
import XML
let xml = #"""
<?xml version="1.0" encoding="UTF-8"?>
<!-- begin greeting -->
<greeting>Hello!</greeting>
<!-- end greeting -->
"""#
let document = try XML.Document(string: xml)!
document.root?.name // "greeting"
document.root?.content // "Hello!"
document.children.count // 3 (two comment nodes and one element node)
document.root?.children.count // 1 (one text node)
document.search("//greeting").count // 1
document.evaluate("//greeting/text()") // .string("Hello!")
for case let comment as Comment in document.children {
comment.remove()
}
document.root?.name = "valediction"
document.root?["lang"] = "it"
document.root?.content = "Arrivederci!"
document.description // =>
/*
<?xml version="1.0" encoding="UTF-8"?>
<valediction lang="it">Arrivederci!</valediction>
*/
import HTML
let html = #"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome</title>
</head>
<body>
<p>Hello, world!</p>
</body>
</html>
"""#
let document = try HTML.Document(string: html)!
document.body?.children.count // 1 (one element node)
document.body?.children.first?.name // "p"
document.body?.children.first?.text // "Hello, world!"
document.search("/body/p").count // 1
document.search("/body/p").first?.xpath // "/body/p[0]"
document.evaluate("/body/p/text()") // .string("Hello, world!")
let div = Element(name: "div")
div["class"] = "wrapper"
if let p = document.search("/body/p").first {
p.wrap(inside: div)
}
document.body?.description // =>
/*
<div class="wrapper">
<p>Hello, world!</p>
</div>
*/
在 Swift 5.3+ 中可用。
import HTML
let document = HTML.Document {
html(["lang": "en"]) {
head {
meta(["charset": "UTF-8"])
title { "Hello, world!" }
}
body(["class": "beautiful"]) {
div(["class": "wrapper"]) {
span { "Hello," }
tag("span") { "world!" }
}
}
}
}
document.description // =>
/*
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello, world!</title>
</head>
<body class="beautiful">
<?greeter start>
<div class="wrapper">
<span>Hello,</span>
<span>world!</span>
</div>
<?greeter end>
</body>
</html>
*/
如果您在 Linux 上,或者您在 macOS 上并使用 Xcode < 11.4,请安装 libxml2 系统库
# macOS for Xcode 11.3 and earlier
$ brew install libxml2
$ brew link --force libxml2
# Linux (Ubuntu)
$ sudo apt-get install libxml2-dev
在 Package.swift
中将 Markup 包添加到您的目标依赖项
import PackageDescription
let package = Package(
name: "YourProject",
dependencies: [
.package(
url: "https://github.com/SwiftDocOrg/Markup",
from: "0.1.2"
),
]
)
将 Markup
作为依赖项添加到您的目标
targets: [
.target(
name: "YourTarget",
dependencies: ["Markup"]),
如果您在应用程序中使用 Markup,请将 libxml2
链接到您的目标。 打开您的 Xcode 项目 (.xcodeproj
) 或工作区 (.xcworkspace
) 文件,在项目导航器中选择您的顶级项目条目,然后在“目标”标题下列出使用 Markup 的目标。 导航到“Build Phases”选项卡,展开“Link Binary With Libraries”,然后单击 + 按钮以添加库。 在搜索栏中输入“libxml2”,从过滤后的列表中选择“libxml2.tbd”,然后单击“添加”按钮。
MIT
Mattt (@mattt)