尝试使用 nokogiri 在 xml 文件中的 cdata 标记中获取内容 [英] trying to get content inside cdata tags in xml file using nokogiri

查看:20
本文介绍了尝试使用 nokogiri 在 xml 文件中的 cdata 标记中获取内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这方面看到了几件事,但到目前为止似乎没有任何效果.我正在使用 rails 3 ruby​​ 1.9.2 上的 nokogiri 通过 url 解析 xml.

I have seen several things on this, but nothing has seemed to work so far. I am parsing an xml via a url using nokogiri on rails 3 ruby 1.9.2.

xml 片段如下所示:

A snippet of the xml looks like this:

<NewsLineText>
  <![CDATA[
  Anna Kendrick is ''obsessed'' with 'Game of Thrones' and loves to cook, particularly     creme brulee.
  ]]>
</NewsLineText>

我正在尝试解析它以获取与 NewsLineText 关联的文本

I am trying to parse this out to get the text associated with the 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

我得到的回报是

<newslinetext></newslinetext>
NOTHING
NOTHING

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

So I know my tags are named/spelled correctly to get at the newslinetext data, but the cdata text never shows up.

我需要对 nokogiri 做什么才能获得此文本?

What do I need to do with nokogiri to get this text?

推荐答案

您正在尝试使用 Nokogiri 的 HMTL 解析器解析 XML.如果 node 来自 XML 解析器,则 r 将是 nil,因为 XML 区分大小写;你的 r 不是 nil 所以你使用的是不区分大小写的 HTML 解析器.

You're trying to parse XML using Nokogiri's HMTL parser. If node as from the XML parser then r would be nil since XML is case sensitive; your r is not nil so you're using the HTML parser which is case insensitive.

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

Use Nokogiri's XML parser and you will get things like this:

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

您将能够通过 r.textr.children 获取 CDATA.

and you'll be able to get at the CDATA through r.text or r.children.

这篇关于尝试使用 nokogiri 在 xml 文件中的 cdata 标记中获取内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆