honghaoz / Ji

Ji (戟) is an XML/HTML parser for Swift
MIT License
824 stars 64 forks source link

add prefix #26

Closed dowhilenet closed 8 years ago

dowhilenet commented 8 years ago

Hi!你好

当我在解析这个的时候 entry [https://github.com/showcases.atom] 总是没有值。

好像是因为 prefix 的原因。请问有什么解决办法吗

谢谢 : ]

honghaoz commented 8 years ago

Hi,你好

你指的是什么prefix? 我试了试这段code

let github = Ji(htmlURL: NSURL(string: "https://github.com/showcases.atom")!)
print(github?.rootNode?.descendantsWithName("entry").first?.rawContent)

出来的结果是

Optional("<entry>\n    <id>tag:github.com,2008:Showcase::Collection/72</id>\n    <published>2015-11-30T20:01:57Z</published>\n    <updated>2016-02-03T18:45:02Z</updated>\n    <link rel=\"alternate\" type=\"text/html\" href=\"https://github.com/showcases/swift\">\n    <title>Swift</title>\n    <category>Swift, C++</category>\n    <url>https://github.com/showcases/swift</url>\n    <content type=\"html\"></content>\n  </entry>")

看起来没问题。

如果你用的xpath,贴出来一起看看?

dowhilenet commented 8 years ago

你好谢谢您能回复我。

代码是这样的

let github = Ji(htmlURL: NSURL(string: "https://github.com/showcases.atom")!)
let entry = github?.xPath("//entry")
let title = entry?.first?.xPath("//title")
print(title)

额。不好意思,不知道为什么昨天总是没有值。刚刚又试了一下,可以了。><

我指的prefix是从 Fuzi这个库看到的。

import Fuzi

let xml = "..."
do {
  // if encoding is omitted, it defaults to NSUTF8StringEncoding
  let doc = try XMLDocument(string: html, encoding: NSUTF8StringEncoding)
  if let root = document.root {
    print(root.tag)

    // define a prefix for a namespace
    document.definePrefix("atom", defaultNamespace: "http://www.w3.org/2005/Atom")

    // get first child element with given tag in namespace(optional)
    print(root.firstChild(tag: "title", inNamespace: "atom"))

    // iterate through all children
    for element in root.children {
      print("\(index) \(element.tag): \(element.attributes)")
    }
  }

.......

发现还是 Ji使用起来比较方便。可能我对Ji还不是很熟悉,使用起来可能会出现很多问题。 :) 期待Ji的css查询功能。

honghaoz commented 8 years ago

嗯嗯,多谢啦,问题解决掉就好了。css我抽空看看吧,最近也挺忙的