2011-09-08 43 views
0

这里编程noob。 想知道从字符串中提取特定位信息的最佳方式是使用Ruby。从ruby中的字符串中提取信息

我有一些XML的,看起来像这样的API:

<users> 
    <user> 
    <twitter_screen_name>Jason</twitter_screen_name> 
    <kscore>81.78</kscore> 
    </user> 
</users> 

我只是想获得的用户名和kscore出来。

继承人我有什么,只是想知道如果一个更有效的方式?不建议

doc  = Nokogiri::XML(your_xml_string) 
username = doc.at('twitter_screen_name').content 
klout = doc.at('kscore').content.to_f 

试图解析使用正则表达式XML:

info = Array.new 
username = info[3].split('>') 
username = username[1].split('<') 
username = username[0] 

klout = info[4].split('>') 
klout = klout[1].split('<') 
klout = klout[0] 

感谢

+0

强制性有趣 “不要解析XML自己” 链接:https://github.com/jasontorres/klout

这将> = 1.9.2的工作: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 –

回答