Ruby 如何使用SAX获取CDATA内容

Ruby 如何使用SAX获取CDATA内容,ruby,xml,nokogiri,sax,Ruby,Xml,Nokogiri,Sax,我试图解析一个大的XML文件,以获取所有外部XML标记内容,如下所示: <string name="key"><![CDATA[Hey I'm a tag with & and other characters]]></string> Hey I\'m a tag with &amp; and other characters tmp = Nokogiri::XML::Document.new value = tmp.create_

我试图解析一个大的XML文件,以获取所有外部XML标记内容,如下所示:

<string name="key"><![CDATA[Hey I'm a tag with & and other characters]]></string>
Hey I\'m a tag with &amp; and other characters
  tmp = Nokogiri::XML::Document.new
  value = tmp.create_cdata(value)
  r = doc.at_xpath(PATH_TO_REPLACE)
  r.inner_html = value
这是我的代码:

  class IDCollector < Nokogiri::XML::SAX::Document
    def initialize
    end

    def characters string
        puts string # this does not works, CDATA tag is not printed  
    end

    def cdata_block string
      puts string
      puts "<![CDATA[" + string + "]]>"
    end
  end
类IDCollector
有没有办法用Nokogiri萨克斯做到这一点

查看文档一段时间后,我认为只有在Nokogiri的帮助下构建一个新的CDATA内容,才能做到这一点,比如:

<string name="key"><![CDATA[Hey I'm a tag with & and other characters]]></string>
Hey I\'m a tag with &amp; and other characters
  tmp = Nokogiri::XML::Document.new
  value = tmp.create_cdata(value)
  r = doc.at_xpath(PATH_TO_REPLACE)
  r.inner_html = value

不清楚你想做什么,但这可能有助于澄清问题

条目不是标记,它是块,解析器会对其进行不同的处理。当遇到块时,
]>
被剥离,因此您只能看到里面的字符串。有关详细信息,请参阅“”

如果您试图用XML创建CDATA块,可以使用以下方法轻松完成:

doc = Nokogiri::XML(%(<string name="key"></string>))
doc.at('string') << Nokogiri::XML::CDATA.new(Nokogiri::XML::Document.new, "Hey I'm a tag with & and other characters")
doc.to_xml # => "<?xml version=\"1.0\"?>\n<string name=\"key\"><![CDATA[Hey I'm a tag with & and other characters]]></string>\n"

使用
internal_html
会导致对字符串进行html编码,这是嵌入可能包含标记的文本的另一种方法。如果没有编码或使用
CDATA
,XML解析器可能会混淆什么是文本,什么是真正的标记。我编写过RSS聚合器,必须处理提要中错误编码的嵌入式HTML是一件痛苦的事情。

不清楚您要做什么:读取或生成CDATA块?您不会得到
实际上是标记,但是它被处理掉了,只返回了它的内容。也许会有帮助。我不能重复获得编码结果。我的最终目标是将一些xml标记及其内部内容移植到其他文件。虽然,文件都很大,我必须使用SAX,否则我有一个内存,但实际上我更喜欢这个(Nokogiri::XML::CDATA.new)而不是我的答案。另外,感谢您描述的答案,它帮助了:)