Swift 版 HTML/XML 解析器 Ji。
解析 NSURL:
let jiDoc = Ji(htmlURL: NSURL(string: "http://www.apple.com/support")!) let titleNode = jiDoc?.xPath("//head/title")?.first print("title: \(titleNode?.content)") // title: Optional("Official Apple Support")解析 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 jiDoc = Ji(xmlString: xmlString) let bodyNode = jiDoc?.rootNode?.firstChildWithName("body") print("body: \(bodyNode?.content)") // body: Optional("Don\'t forget me this weekend!")解析 NSData:
let googleIndexData = NSData(contentsOfURL: NSURL(string: "http://www.google.com")!) if let googleIndexData = googleIndexData { let jiDoc = Ji(htmlData: googleIndexData)! let htmlNode = jiDoc.rootNode! print("html tagName: \(htmlNode.tagName)") // html tagName: Optional("html") let aNodes = jiDoc.xPath("//body//a") if let firstANode = aNodes?.first { print("first a node tagName: \(firstANode.name)") // first a node tagName: Optional("a") let href = firstANode["href"] print("first a node href: \(href)") // first a node href: Optional("http://www.google.ca/imghp?hl=en&tab=wi") } } else { print("google.com is inaccessible") } let 戟文檔 = 戟(htmlURL: NSURL(string: "https://cocoapods.org/pods/Ji")!) let attribution = 戟文檔?.xPath("//ul[@class='attribution']")?.first print("作者(Author): \(attribution?.content)")