English 中文(简体)
How to add non-escaped ampersands to HTML with Nokogiri::XML::Builder
原标题:

I would like to add things like bullet points "•" 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> 

I m just doing this:

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

What am I missing?

最佳回答

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.

问题回答

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 xe2x80xa2 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.)





相关问题
CSS working only in Firefox

I am trying to create a search text-field like on the Apple website. The HTML looks like this: <div class="frm-search"> <div> <input class="btn" type="image" src="http://www....

image changed but appears the same in browser

I m writing a php script to crop an image. The script overwrites the old image with the new one, but when I reload the page (which is supposed to pickup the new image) I still see the old one. ...

Firefox background image horizontal centering oddity

I am building some basic HTML code for a CMS. One of the page-related options in the CMS is "background image" and "stretch page width / height to background image width / height." so that with large ...

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签