Swift 2.0 輕量快速的XML/HTML解析器Fuzi

cezheng 9年前發布 | 15K 次閱讀 XML HTML Swift IOS 開源 Apple Swift開發 Github

iOS下的NSXMLParser易用性較差,而且效率也偏低。因此Matt Thompson大神曾經用Objective-C寫了一個叫Ono的解析器,封裝了libxml2,從易用性和執行方便都遠優于NSXMLParser。用Objective-C實現的Ono在Swift的應用里雖然可以使用,卻有諸多不便。因此鄙人參照了Ono對libxml2的封裝方式,對類和方法進行了重新設計弄出了這個小庫。同時修正了Ono存在的一些邏輯上和內存管理方面的bug。

項目地址: https://github.com/cezheng/Fuzi

詳情請見中文README: https://github.com/cezheng/Fuzi/blob/master/README-zh.md

例子
let xml = "..."
do {
  let document = try XMLDocument(string: xml)

  if let root = document.root {
    // Accessing all child nodes of root element
    for element in root.children {
      print("\(element.tag): \(element.attributes)")
    }

    // Getting child element by tag & accessing attributes
    if let length = root.firstChild(tag:"Length", inNamespace: "dc") {
      print(length["unit"])     // `unit` attribute
      print(length.attributes)  // all attributes
    }
  }

  // XPath & CSS queries
  for element in document.xpath("") {
    print("\(element.tag): \(element.attributes)")
  }

  if let firstLink = document.firstChild(css: "a, link") {
    print(firstLink["href"])
  }
} catch let error {
  print(error)
}

支持CocoaPods或者Carthage等包管理器

CoacoaPods
pod 'Fuzi', '~> 0.1.0'

Carthage
github "cezheng/Fuzi" ~> 0.1.0

 本文由用戶 cezheng 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!