代码之家  ›  专栏  ›  技术社区  ›  astropanic

Nokogiri在段落中查找文本

  •  5
  • astropanic  · 技术社区  · 15 年前

    我想替换XHTML文档中所有段落的内部文本。

    我知道我可以像这样和诺科吉拉一起收到所有的短信

    doc.xpath("//text()")
    

    但我只想操作段落中的文本,如何选择段落中的所有文本而不影响链接中最终存在的锚文本?

    #For example : <p>some text <a href="/">This should not be changed</a> another one</p>
    
    1 回复  |  直到 15 年前
        1
  •  6
  •   jeem    15 年前

    对于段落的直接子级文本,请使用//p/text()。

    irb> h = '<p>some text <a href="/">This should not be changed</a> another one</p>'
    => ...
    irb> doc = Nokogiri::HTML(h)
    => ...
    irb> doc.xpath '//p/text()'
    => [#<Nokogiri::XML::Text:0x80ac2e04 "some text ">, #<Nokogiri::XML::Text:0x80ac26c0 " another one">]
    

    对于段落的子代(直接或非直接)文本,请使用//p//text()。要排除那些有锚定作为父级的文本,您只需减去它们即可。

    irb> doc.xpath('//p//text()') - doc.xpath('//p//a/text()')
    => [#<Nokogiri::XML::Text:0x80ac2e04 "some text ">, #<Nokogiri::XML::Text:0x80ac26c0 " another one">]
    

    可能有一种方法可以通过一个调用来完成,但是我的XPath知识并没有深入。