直接来个简单的代码实例就明白啦!
require 'nokogiri' xml_data=<<XML
<library>
<NAME><![CDATA[Favorite Books]]></NAME>
<book ISBN="">
<title>To Kill A Mockingbird</title>
<description><![CDATA[Description#1]]></description>
<author>Harper Lee</author>
</book>
<book ISBN="">
<title>Catcher in the Rye</title>
<description><![CDATA[This is an extremely intense description.]]></description>
<author>J. D. Salinger</author>
</book>
<book ISBN="">
<title>Murphy\'s Gambit</title>
<description><![CDATA[Daughter finds her dad!]]></description>
<author>Syne Mitchell</author>
</book>
</library>
XML # 载入数据
doc = Nokogiri::XML(xml_data) # 使用css获取到结点,遍历读取到Book对象中
doc.css('book').each do |node|
children = node.children Book.create(
:isbn => node['ISBN'],
:title => children.css('title').inner_text,
:description => children.css('description').inner_text,
:author => children.css('author').inner_text
)
end