Is there a way to select all the contents of a node?

我的未来我决定 提交于 2020-01-15 09:20:51

问题


Is there a way to select all the contents of a node in Nokogiri?

<root>
    <element>this is <hi>the content</hi> of my æøå element</element>
</root>

The result of getting the content of /root/element should be:

this is <hi>the content</hi> of my æøå element

Edit:

It seems like the solution is simply to use myElement.inner_html(). The problem I had was in fact that I was relying on an old version of libxml2, which escaped all the special characters.


回答1:


Nokogiri.parse('<root><element>this is <hi>the content</hi> of my element</element></root>').css('element').inner_html

If you want escape that, you can with CGI.unescape method:

require 'cgi'
x = Nokogiri.parse('<root><element>this is <hi>the content</hi> of my element</element></root>').css('element').inner_html
CGI.unescape(x)



回答2:


I think the previous answer is assuming HTML. I'm not sure that's appropriate, so here's my (similar) answer:

require 'nokogiri'
xml = '<root><element>this is <hi>the content</hi> of my æøå element</element></root>' 
p Nokogiri(xml).at('element').to_xml


来源:https://stackoverflow.com/questions/2524305/is-there-a-way-to-select-all-the-contents-of-a-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!