【问题标题】:Is there a way to select all the contents of a node?有没有办法选择一个节点的所有内容?
【发布时间】:2011-02-01 05:32:43
【问题描述】:

有没有办法在 Nokogiri 中选择一个节点的所有内容?

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

获取/root/element的内容的结果应该是:

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

编辑:

似乎解决方案只是使用myElement.inner_html()。我遇到的问题实际上是我依赖的是旧版本的 libxml2,它转义了所有特殊字符。

【问题讨论】:

    标签: xml ruby utf-8 nokogiri


    【解决方案1】:
    Nokogiri.parse('<root><element>this is <hi>the content</hi> of my element</element></root>').css('element').inner_html
    

    如果你想逃避它,你可以使用CGI.unescape 方法:

    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)
    

    【讨论】:

    • Nokogiri.parse('this is the content of my æøå element').css('element' ).inner_html.inspect => "\"这是我的 内容 æøå元素\""
    • 你可以 CGI.unescape 结果
    • 嗯,也许未转义适用于您的测试用例,但您可能会取消转义最初未转义的内容。可能会看看loofah gem 在这种情况下是否有帮助。
    【解决方案2】:

    我认为前面的答案是假设 HTML。我不确定这是否合适,所以这是我的(类似)答案:

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

    【讨论】:

      猜你喜欢
      • 2010-10-24
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多