Swift 版 HTML/XML 解析器 Ji

本文介绍了Swift中的HTML和XML解析库Ji,通过实例展示了如何加载网页数据并进行XPath查询,获取元素内容和属性,以及从字符串初始化XML文档。Ji提供了一种简单易用的方式来处理网页和XML文档。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Ji框架的地址:https://github.com/honghaoz/Ji

    pod 'Ji', '~> 2.0.1'



import UIKit


class ViewController: UIViewController {


overridefunc viewDidLoad() {

super.viewDidLoad()

// Init with data

let googleIndexData =try? Data(contentsOf:URL(string: "http://www.google.com")!)

iflet googleIndexData = googleIndexData {

let jiDoc =Ji(htmlData: googleIndexData)!

let htmlNode = jiDoc.rootNode!

print("html tagName:\(htmlNode.tagName)")

let aNodes = jiDoc.xPath("//body//a")

iflet firstANode = aNodes?.first {

print("first a node tagName:\(firstANode.name)")

let href = firstANode["href"]

print("first a node href:\(href)")

}

} else {

print("google.com is inaccessible")

}

print("")

// Init with URL

let jiAppleSupportDoc =Ji(htmlURL: URL(string:"http://www.apple.com/support")!)

let titleNode = jiAppleSupportDoc?.xPath("//head/title")?.first

print("title:\(titleNode?.content)")

print("")

// Init with String

let xmlString ="<?xml version='1.0' encoding='UTF-8'?><note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>"

let xmlDoc =Ji(xmlString: xmlString)

let bodyNode = xmlDoc?.rootNode?.firstChildWithName("body")

print("body:\(bodyNode?.content)")

print("")

// Just for fun

let戟文档 =(htmlURL:URL(string: "https://cocoapods.org/pods/Ji")!)

let attribution =戟文档?.xPath("//ul[@class='attribution']")?.first

print("作者(Author):\(attribution?.content)")

}

}



结果:

html tagName: Optional("html")

first a node tagName: Optional("a")

first a node href: Optional("http://www.google.co.jp/imghp?hl=zh-CN&tab=wi")


title: Optional("Official Apple Support")


body: Optional("Don\'t forget me this weekend!")


作者(Author): Optional("ByHonghao Zhang")




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值