开发者

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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜