2010-05-08 87 views
5

我想在我的XHTML文檔的所有段落中替換inner_text。Nokogiri在段落中找到文本

我知道我能得到的所有文字與引入nokogiri這樣

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

但我只想要,我怎麼能選擇的段落中的所有文本,而不會影響最終的鏈接存在的錨文本的段落文本操作?

#For example : <p>some text <a href="/">This should not be changed</a> another one</p> 
+0

如果最後的標籤是'

',要關閉'

'標籤,而不是''? – michaelmichael 2010-05-08 17:54:40

+0

根據任何定義,選擇不應該影響任何東西。 「選擇而不影響」是什麼意思? – 2010-05-08 19:37:48

+0

@michaelmichael - 當然,你說得對,我已經糾正了最後一個結束標記 – astropanic 2010-05-09 16:23:01

回答

5

對於文本,其是一個段落使用// P /文本()的直接子

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的(立即或不) //文本()。要排除那些有錨點的文本,您可以將它們減去。

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

有一種方法可以通過一次調用來完成,但是我的xpath知識並沒有那麼深入。

+0

非常聰明,很好,謝謝你 – astropanic 2010-05-09 16:23:58