尝试使用nokogiri在xml文件中获取cdata标签内的内容

Aar*_*mas 15 ruby cdata nokogiri xml-parsing ruby-on-rails-3.1

我已经看到了几件事,但到目前为止似乎没有任何工作.我在rails 3 ruby​​ 1.9.2上使用nokogiri通过url解析xml.

xml的片段如下所示:

<NewsLineText>
  <![CDATA[
  Anna Kendrick is ''obsessed'' with 'Game of Thrones' and loves to cook, particularly     creme brulee.
  ]]>
</NewsLineText>
Run Code Online (Sandbox Code Playgroud)

我试图解析这个以获取与NewsLineText相关联的文本

r = node.at_xpath('.//newslinetext') if node.at_xpath('.//newslinetext')
s = node.at_xpath('.//newslinetext').text if node.at_xpath('.//newslinetext')
t = node.at_xpath('.//newslinetext').content if node.at_xpath('.//newslinetext')
puts r
puts s ? if s.blank? 'NOTHING' : s
puts t ? if t.blank? 'NOTHING' : t
Run Code Online (Sandbox Code Playgroud)

我得到的回报是

<newslinetext></newslinetext>
NOTHING
NOTHING
Run Code Online (Sandbox Code Playgroud)

所以我知道我的标签被正确命名/拼写以获取newslinetext数据,但cdata文本永远不会出现.

我需要用nokogiri来获取此文本?

mu *_*ort 13

您正在尝试使用Nokogiri的HMTL解析器解析XML.如果node从XML解析器那么r将是nil因为XML区分大小写; 你r不是nil在使用不区分大小写的HTML解析器.

使用Nokogiri的XML解析器,你会得到这样的东西:

>> r = doc.at_xpath('.//NewsLineText')
=> #<Nokogiri::XML::Element:0x8066ad34 name="NewsLineText" children=[#<Nokogiri::XML::Text:0x8066aac8 "\n  ">, #<Nokogiri::XML::CDATA:0x8066a9c4 "\n  Anna Kendrick is ''obsessed'' with 'Game of Thrones' and loves to cook, particularly     creme brulee.\n  ">, #<Nokogiri::XML::Text:0x8066a8d4 "\n">]>
>> r.text
=> "\n  \n  Anna Kendrick is ''obsessed'' with 'Game of Thrones' and loves to cook, particularly     creme brulee.\n  \n"
Run Code Online (Sandbox Code Playgroud)

你将能够通过r.text或获得CDATA r.children.