Rendering XML with Stylesheet in Rails - ruby-on-rails

I can't figure out how to get a rendered collection (as XML) to include a style sheet line such as:
<?xml-stylesheet type="text/xsl" href="example.xsl" ?>
This guy says to add a proc as such:
proc = Proc.new { |options| options[:builder].instruct!(:xml-stylesheet, type=>'text/xsl', :href=>'something.xsl') }
#foo.to_xml :procs => [proc]
But I can't get that to work. Any suggestions?

Take a look at Nokogiri gem: http://nokogiri.org/Nokogiri/XSLT/Stylesheet.html
doc = Nokogiri::XML(File.read('some_file.xml'))
xslt = Nokogiri::XSLT(File.read('some_transformer.xslt'))
puts xslt.transform(doc)

You can use the atom_feed helper which is included with Rails:
atom_feed(instruct: {
'xml-stylesheet' => {type: 'text/xsl', href: 'styles.xml'}
}) do |feed|
feed.title "My Atom Feed"
# entries...
end
Which results in (showing only first 3 lines):
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="styles.xml"?>
<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom">
Or, if not rendering an atom_feed, you can simply use instruct inside your builder:
xml.instruct! 'xml-stylesheet', href: 'style.xml', type: 'text/xsl'

Related

ruby to_xml set root attributes

I need to convert a ruby hash to xml. Here is the hash:
hash = {
"AffiliateInfo" => {
"Username" => '123456',
"Password" => "Mypass",
"TrackingCampaign" => "MyTrackingCampaign",
"Env" => "production"
}
}
and the xml I wanted to generate:
<?xml version="1.0" encoding="UTF-8"?>
<InsuranceRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<AffiliateInfo>
<Username>12696</Username>
<Password>MyPassword</Password>
<TrackingCampaign>MyTrackingCampaign</TrackingCampaign>
<LeadSourceID>SourceID</LeadSourceID>
<ProductionEnvironment>true</ProductionEnvironment>
</AffiliateInfo>
</InsuranceRequest>
When I do:
hash.to_xml(root: 'InsuranceRequest')
I get the following xml output
<?xml version="1.0" encoding="UTF-8"?>
<InsuranceRequest>
<AffiliateInfo>
<Username>123456</Username>
<Password>Mypass</Password>
<TrackingCampaign>MyTrackingCampaign</TrackingCampaign>
<Env>production</Env>
</AffiliateInfo>
</InsuranceRequest>
The output is missing the properties of the root node attributes:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
I cannot add attributes to the root node. Is there a way to add these attributes using to_xml method?
Please suggest if there is any other means to solve my problem.
You need to use custom builder. Here is example with Nokogiri builder
require 'nokogiri'
hash = {"AffiliateInfo" => {
"Username" => '123456',
"Password" => "Mypass",
"TrackingCampaign" => "MyTrackingCampaign",
"Env" => "production"
}
}
builder = Nokogiri::XML::Builder.new do |xml|
xml.InsuranceRequest('xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance', 'xmlns:xsd' => 'http://www.w3.org/2001/XMLSchema') do
xml.AffiliateInfo do
hash['AffiliateInfo'].each do |k, v|
xml.send(k, v)
end
end
end
end
builder.to_xml
This produces the following XML document
<?xml version="1.0"?>
<InsuranceRequest
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<AffiliateInfo>
<Username>123456</Username>
<Password>Mypass</Password>
<TrackingCampaign>MyTrackingCampaign</TrackingCampaign>
<Env>production</Env>
</AffiliateInfo>
</InsuranceRequest>
Please note that hash should be defined before builder
Here is Nokogiri documentation http://www.rubydoc.info/github/sparklemotion/nokogiri/Nokogiri/XML/Builder

Generating iTunes XML nodes in RSS feed using Ruby/Rails

Q: How do I generate the XML nodes specific to iTunes using Ruby/Rails?
Trying to generate iTunes XML feed, e.g. (based off example):
xml.instruct! :xml, :version => "1.0"
xml.rss(:version => "2.0") do
xml.channel do
xml.title "Your Blog Title"
xml.description "A blog about software and chocolate"
xml.link posts_url
#posts.each do |post|
xml.item do
xml.title post.title
xml.description "Temporary post description"
xml.pubDate post.created_at.to_s(:rfc822)
xml.link post_url(post)
xml.guid post_url(post)
end
end
end
end
Which happily generates something like:
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
<title>Your Blog Title</title>
<description>A blog about software and chocolate</description>
<link>https://pubweb-thedanielmay.c9.io/sermons</link>
<item>
... omitted ...
</item>
</channel>
</rss>
But looks like I need to generate iTunes-specific XML nodes (as per Working With iTunes, e.g.)
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" version="2.0"> <-- *
<channel>
<title>Your Blog Title </title>
... omitted ...
<itunes:subtitle>A program about everything</itunes:subtitle> <-- *
... etc ...
Not sure how I generate the iTunes-specific nodes as they have colons in them.
Standard RSS nodes are like:
xml.item --> <item>
How do I get to generating nodes like:
<rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" version="2.0">
<itunes:author>
Ah, answers as per code via Ryan Bates' awesome Railscasts RSS sample
xml.rss "xmlns:itunes" => "http://www.itunes.com/dtds/podcast-1.0.dtd", :version => "2.0"
and
xml.itunes :author, author

How to change Rails 3 to_xml encoding

Im using Rails 3 to_xml on a Model with a few options like include, except and methods.
So this is not my first time using to_xml.
I'm doing something like this:
to_xml(include: {
order: {
methods: [:my_avg],
except: [:this_attr, :and_this_attr ]
},
customer: {}
})
The XML result:
<?xml version="1.0" encoding="UTF-8"?>
<my-model>
<attr1 type="integer">12</attr1>
<attr2 type="integer">12</attr2>
<order>
<name>foo</name>
<desc>bar</desc>
<my-avg>
<avg type="integer">123</avg>
<foo>ok</foo>
</my-avg>
</order>
<updated-at type="datetime">2014-04-14T11:16:56-03:00</updated-at>
</my-model>
But now I want to change the xml encoding ISO_8859_1 instead of utf8.
I haven't seen an encoding option on ActiveRecord::Serialization module.
If I simply add one encoding option it creates a XML attribute instead of changing the encoding that results on this XML:
<?xml version="1.0" encoding="UTF-8"?>
<my-model>
<attr1 type="integer" encoding="ISO-8859-1">12</attr1>
<attr2 type="integer" encoding="ISO-8859-1">12</attr2>
<order>
<name>foo</name>
<desc>bar</desc>
<my-avg>
<avg type="integer">123</avg>
<foo>ok</foo>
</my-avg>
</order>
<updated-at type="datetime">2014-04-14T11:16:56-03:00</updated-at>
</my-model>
Is there a way to specify the encoding using ActiveRecord's to_xml?
you may override to_xml in your Model & specify encoding. something like this could work:
class ModelName < ActiveRecord::Base
def to_xml(options = {})
require 'builder'
options[:indent] ||= 2
xml = options[:builder] ||= ::Builder::XmlMarkup.new(indent: options[:indent])
xml.instruct! :xml, :version=>"1.0", :encoding => "ISO-8859-1"
xml.level_one do
xml.tag!(:second_level, 'content')
end
end
end

Rails XML Feed: ID as node attribute

I set up a simple XML feed for a vendor we're using (who refuses to read JSON).
<recipes type="array">
<recipe>
<id type="integer">1</id>
<name>
Hamburgers
</name>
<producturl>
http://test.com
</producturl>
...
</recipe>
...
<recipe>
However, the vendor requests that instead of having an id node, id is an attribute in the parent node. e.g.
<recipes type="array">
<recipe id="1">
<name>
Hamburgers
</name>
<producturl>
http://test.com
</producturl>
...
</recipe>
...
<recipe>
I'm building this with (basically)
xml_feed = []
recipes.each do |recipe|
xml_feed <<{id: recipe.id, name: recipe.name, ...}
end
...
render xml: xml_feed.to_xml(root: 'recipes')
But I'm unsure of how to include the id (or any field) as an attribute in the parent node like that. I googled around and couldn't find anything, nor were the http://api.rubyonrails.org/classes/ActiveRecord/Serialization.html docs very helpful
Thanks!
I would suggest you use the nokogiri gem. It provides all you can possible need for handling XML.
builder = Nokogiri::XML::Builder.new do |xml|
xml.root {
xml.objects {
xml.object.classy.thing!
}
}
end
puts builder.to_xml
<?xml version="1.0"?>
<root>
<objects>
<object class="classy" id="thing"/>
</objects>
</root>
The suggestion to use Nokogiri is fine. Just the sintax should be a little bit different to achive what you have requested:
builder = Nokogiri::XML::Builder.new do |xml|
xml.root {
xml.object('type' => 'Client') {
xml.name 'John'
}
}
end
puts builder.to_xml
<?xml version="1.0"?>
<root>
<object type="Client">
<name>John</name>
</object>
</root>

What can I use to generate a local XML file?

I have a project that I am working on and I do not know much about Rails or Ruby.
I need to generate an XML file from user input.
Can some direct me to any resource that can show me how to do this pretty quickly and easily?
The Nokogiri gem has a nice interface for creating XML from scratch. It's powerful while still easy to use. It's my preference:
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
Will output:
<?xml version="1.0"?>
<root>
<products>
<widget>
<id>10</id>
<name>Awesome widget</name>
</widget>
</products>
</root>
Also, Ox does this too. Here's a sample from the documenation:
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>
Nokogiri is a wrapper around libxml2.
Gemfile
gem 'nokogiri'
To generate xml simple use the Nokogiri XML Builder like this
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
The result will look like
<?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>
Source: http://www.jakobbeyer.de/xml-with-nokogiri

Resources