views:

480

answers:

2

I would like to add things like bullet points "•" and such to html using the XML Builder in Nokogiri, but everything is being escaped. How do I prevent it from being escaped?

I would like the result to be:


<span>&#8226;</span> 
rather than


<span>&amp;#8226;</span> 

What am I missing?

I'm just doing this:


xml.span { 
  xml.text "&#8226;\ " 
}

Thanks!

A: 

When you're setting the text of an element, you really are setting text, not HTML source. < and & don't have any special meaning in plain text.

So just type a bullet: '•'. Of course your source code and your XML file will have to be using the same encoding for that to come out right. If your XML file is UTF-8 but your source code isn't, you'd probably have to say '\xe2\x80\xa2' which is the UTF-8 byte sequence for the bullet character as a string literal.

(In general non-ASCII characters in Ruby 1.8 are tricky. The byte-based interfaces don't mesh too well with XML's world of all-text-is-Unicode.)

bobince
I need to have the result with "•", so '\xe2\x80\xa2' isn't working :/
viatropos
Why do you *need* that particular escaped version? If you are having encoding troubles so the • doesn't appear like you type it, then you should try to fix those by setting your encoding right rather than resorting to HTML-escapes. (Whilst in other environments you might ask your HTML serialiser to escape all non-ASCII characters to HTML-ampersand-sequences to get around this, Ruby doesn't currently have that level of Unicode support.)
bobince
A: 

If you define

  class Nokogiri::XML::Builder
    def entity(code)
      doc = Nokogiri::XML("<?xml version='1.0'?><root>&##{code};</root>")
      insert(doc.root.children.first)
    end
  end

then this

  builder = Nokogiri::XML::Builder.new do |xml|
    xml.span {
      xml.text "I can has "
      xml.entity 8665
      xml.text " entity?"
    }
  end
  puts builder.to_xml

yields

<?xml version="1.0"?>
<span>I can has &#x2022; entity?</span>

 

PS this a workaround only, for a clean solution please refer to the libxml2 documentation (Nokogiri is built on libxml2) for more help. However, even these folks admit that handling entities can be quite ..err, cumbersome sometimes.

Adrian
thanks adrian, what is an "entity", and where'd you get 8665?
viatropos
if I do 8226 instead of 8665, it parses it to "bull;" :/
viatropos
Oops, I mistook 8665 for 8226! Entity is the proper name for `` sequences. `•` should be okay, it's the official name of that entity in HTML. `<!ENTITY bull CDATA "•" -- bullet, =black small circle, u+2022 ISOpub -->` see http://www.w3.org/TR/WD-html40-970708/sgml/entities.html
Adrian