如何在rails中搜索特定的字符串?

时间:2012-04-12 12:44:40

标签: ruby-on-rails

我已经如下所示,我想搜索一个特定的字符串,它是如何在rails中执行此操作的。

例如:我想搜索 Nokogiri :: XML :: Text 模式并获得所有模式匹配 Nokogiri :: XML :: Text

#<LinkedIn::Location:0x4a339e8 @doc=#<Nokogiri::XML::Document:0x2519cb8 name="document" children=[#<Nokogiri::XML::Element:0x2519a0c name="per
son" children=[#<Nokogiri::XML::Text:0x25197f0 "\n  ">, #<Nokogiri::XML::Element:0x251970c name="`" children=[#<Nokogiri::XML::Text:0x2
519124 "\n    ">, #<Nokogiri::XML::Element:0x25190f4 name="name" children=[#<Nokogiri::XML::Text:0x2518bd8 "Bengaluru Area, India">]>, #<Nokog
iri::XML::Text:0x2518b00 "\n    ">, #<Nokogiri::XML::Element:0x2518ad0 name="country" children=[#<Nokogiri::XML::Text:0x2518680 "\n      ">, #
<Nokogiri::XML::Element:0x2518650 name="code" children=[#<Nokogiri::XML::Text:0x2517fcc "in">]>, #<Nokogiri::XML::Text:0x2517eb8 "\n    ">]>,
#<Nokogiri::XML::Text:0x2517cd8 "\n  ">]>, #<Nokogiri::XML::Text:0x2517bdc "\n">]>]>>

1 个答案:

答案 0 :(得分:1)

您可以获得如下值:

方式1:

reader = Nokogiri::XML::Reader(xml)
reader.read #Moves to next node in document
reader.attribute("cdn") # To get the value of attributes

方式2:

doc = Nokogiri::XML(xml)
elems = doc.xpath("//*[@messageId]") #get all elements with an attribute of 'messageId'
elems[0].attr('messageId') #gets value of attribute of first elem