Zigu
Zigu

Reputation: 1665

Ruby on rails string parsing

I have a string that is a bunch of XML tags.

Basically there is the contents to one tag I want and ignore everything else:

The input would look like:

<Some><XML><stuff>
<title type='text'>key</title>
<Some><other><XML><stuff>

The output would look like:

key

I'm not sure if XML is appropriate since there doesn't seem very much structure to this particular XML.

Can regex do this in RoR or is it more of just a pattern matching thing (true or false) in ruby on rails?

Thanks so much!

Cheers, Zigu

Upvotes: 1

Views: 1176

Answers (2)

lbz
lbz

Reputation: 9728

No. If your source could not be strictly valid XML, I strongly suggest you to use Nokogiri.

Handle the source as an HTML document and extract the info you need in this way:

doc = Nokogiri::HTML("Your string with <key>some value</key>"))
doc.search('key').each do |value|
  puts value.content # do whatever you want
end

Upvotes: 2

noodl
noodl

Reputation: 17378

Here's why you don't parse xml with regexen: RegEx match open tags except XHTML self-contained tags

Upvotes: 0

Related Questions