开发者

Ruby on rails string parsing

开发者 https://www.devze.com 2023-01-27 02:16 出处:网络
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:

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

精彩评论

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