iro*_*s7x 4 ruby xml ruby-on-rails xml-builder
我有一个我正在研究的项目,我对Rails或Ruby不太了解.
我需要从用户输入生成XML文件.有人可以指导我使用任何可以快速,轻松地告诉我如何做到这一点的资源吗?
the*_*Man 13
在引入nokogiri宝石有从头开始创建XML一个漂亮的界面.它功能强大,但仍然易于使用.这是我的偏好:
require 'nokogiri'
builder = Nokogiri::XML::Builder.new do |xml|
xml.root {
xml.products {
xml.widget {
xml.id_ "10"
xml.name "Awesome widget"
}
}
}
end
puts builder.to_xml
Run Code Online (Sandbox Code Playgroud)
将输出:
<?xml version="1.0"?>
<root>
<products>
<widget>
<id>10</id>
<name>Awesome widget</name>
</widget>
</products>
</root>
Run Code Online (Sandbox Code Playgroud)
此外,牛也这样做.以下是文档中的示例:
require 'ox'
doc = Ox::Document.new(:version => '1.0')
top = Ox::Element.new('top')
top[:name] = 'sample'
doc << top
mid = Ox::Element.new('middle')
mid[:name] = 'second'
top << mid
bot = Ox::Element.new('bottom')
bot[:name] = 'third'
mid << bot
xml = Ox.dump(doc)
# xml =
# <top name="sample">
# <middle name="second">
# <bottom name="third"/>
# </middle>
# </top>
Run Code Online (Sandbox Code Playgroud)
Nokogiri 是 libxml2 的包装器。
Gemfile gem 'nokogiri' 要生成 xml,只需使用 Nokogiri XML Builder,如下所示
xml = Nokogiri::XML::Builder.new { |xml|
xml.body do
xml.node1 "some string"
xml.node2 123
xml.node3 do
xml.node3_1 "another string"
end
xml.node4 "with attributes", :attribute => "some attribute"
xml.selfclosing
end
}.to_xml
Run Code Online (Sandbox Code Playgroud)
结果看起来像
<?xml version="1.0"?>
<body>
<node1>some string</node1>
<node2>123</node2>
<node3>
<node3_1>another string</node3_1>
</node3>
<node4 attribute="some attribute">with attributes</node4>
<selfclosing/>
</body>
Run Code Online (Sandbox Code Playgroud)
资料来源: http: //www.jakobbeyer.de/xml-with-nokogiri
| 归档时间: |
|
| 查看次数: |
6303 次 |
| 最近记录: |