Umesh Malhotra
Umesh Malhotra

Reputation: 1047

How to write HTML entities using Rails Nokogiri gem?

I was using Nokogiri gem to write some xml data. I need a tag like this:-

<CURRENCYNAME>₹</CURRENCYNAME>

The problem is that Nokogiri writes symbol code (₹) instead of ₹. Below is a snippet from my code:-

  data = Nokogiri::XML::Builder.new do |xml|
          xml.CURRENCYNAME "₹"
         end
  response.headers["file_name"] = "Master.xml"
  send_data data.to_xml, filename: "Master.xml", type: "application/xml"

Result that I get in my Master.xml file:-

<CURRENCYNAME>&#x20B9;</CURRENCYNAME>

Upvotes: 1

Views: 218

Answers (1)

Alex Strizhak
Alex Strizhak

Reputation: 990

use encoding as argument for to_xml method:

irb(main):013:0> Nokogiri::XML::Builder.new { |xml|xml.CURRENCYNAME "₹" }.to_xml(encoding: 'UTF-8')

=> "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<CURRENCYNAME>₹</CURRENCYNAME>\n"

Upvotes: 1

Related Questions