【问题标题】:Hpricot search all the tags under one specific namespaceHpricot 搜索一个特定命名空间下的所有标签
【发布时间】:2011-11-05 02:37:28
【问题描述】:

例如我有以下代码:

<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <title><io:content part="title" /></title>
  <link rel="icon" href="/document/7e9f29e2-cdee-4f85-ba25-132fa867aa90/latest" type="image/x-icon" />
  <n1:content description="Standard CSS" uuid="d069071c-3534-4945-9fb6-2d7be35a165e" />
  <n1:term>Content Development</n1:term>
</head>

这个 XHTML sn-p 不是严格合法的,因为之前没有声明命名空间,所以我不能使用具有更好命名空间支持的 Nokogiri。

我想做一个单一的搜索,可以找到节点 &lt;n1:content&gt;&lt;n1:term&gt; 以及“n1”命名空间下的所有标签。

如何做到这一点?谢谢!

【问题讨论】:

    标签: parsing xhtml jruby xml-namespaces hpricot


    【解决方案1】:

    看起来 Hpricot 并没有完全处理命名空间。

    无论前缀如何,您都可以选择是否知道元素:

    doc.search("title")
    => #<Hpricot::Elements[{elem <title> {emptyelem <io:content part="title">} </title>}]>
    

    ...但这不是你问的。

    这是我的 hack 解决方法:首先使用正则表达式查找所有命名空间元素,然后使用 Hpricot 搜索那些:

    elems = doc.to_s.scan(/<\s*(n1:\w+)/).uniq.join("|")
    => "n1:content|n1:term"
    doc.search(elems)
    => #<Hpricot::Elements[{emptyelem <n1:content description="Standard CSS" uuid="d069071c-3534-4945-9fb6-2d7be35a165e">}, {elem <n1:term> "Content Development" </n1:term>}]>
    

    【讨论】:

    • 谢谢。我通过以下方式解决了问题:traverse_element(*@io_tags)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 2012-08-29
    • 2010-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多