代码之家  ›  专栏  ›  技术社区  ›  Sasha Shpota A-Bag

XPath:在文本节点中查找节点

  •  1
  • Sasha Shpota A-Bag  · 技术社区  · 6 年前

    <code>The first code block</code>
    <p>Some text and <code>the second code block</code> followed by other text</p>
    

    我需要找到并移除所有 code 离它有几个街区。我使用以下XPath '//code' ,但它只找到第一个代码块,而第二个代码块仍然存在。

    为什么? “//代码” 无法捕获第二个代码块?如何修复?

    我是用Ruby做的 Nokagiry . 我的代码如下所示:

    html = Nokogiri::HTML(File.read(htmlFile))
    html.search('//code').remove
    

    更新:

    XPath实际上起了作用。我只是在不同的地方犯了个错误。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Ivan Olshansky    6 年前

    好像你忘了迭代器。。。
    尝试:

    html = Nokogiri::HTML(File.read(htmlFile))
    html.search('//code').each{|htm| htm.remove}