删除标签但保留文本 [英] Remove a tag but keep the text
本文介绍了删除标签但保留文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
So I have this <a>
tag in a xml file
<a href="/www.somethinggggg.com">Something 123</a>
我想要的结果是使用 Nokogiri 并完全删除其标签,使其不再是可点击的链接,例如
My desired result is to use Nokogiri and completely remove its tag so it is no longer a clickable link e.g
Something 123
我的尝试:
content = Nokogiri::XML.fragment(page_content)
content.search('.//a').remove
但这也会删除文本.
关于如何使用 Nokogiri 达到我想要的结果有什么建议吗?
Any suggestions on how to achieve my desired result using Nokogiri?
推荐答案
我会这样做:
require 'nokogiri'
doc = Nokogiri::HTML.parse <<-eot
<a href="/www.somethinggggg.com">Something 123</a>
eot
node = doc.at("a")
node.replace(node.text)
puts doc.to_html
输出
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org
/TR/REC-html40/loose.dtd">
<html>
<body>Something 123</body>
</html>
更新
如果我有一个包含链接内容的数组怎么办?
What if I have an array that holds content with links?
提示
require 'nokogiri'
doc = Nokogiri::HTML.parse <<-eot
<a href="/www.foo.com">foo</a>
<a href="/www.bar.com">bar</a>
<a href="/www.baz.com">baz</a>
eot
arr = %w(foo bar baz)
nodes = doc.search("a")
nodes.each {|node| node.replace(node.content) if arr.include?(node.content) }
puts doc.to_html
输出
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org
/TR/REC-html40/loose.dtd">
<html>
<body>foo
bar
baz
</body>
</html>
这篇关于删除标签但保留文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文