How to add non-escaped ampersands to HTML with Nokogiri::XML::Builder

后端 未结 2 1308
长情又很酷
长情又很酷 2021-01-20 06:52

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

2条回答
  •  长情又很酷
    2021-01-20 07:54

    If you define

      class Nokogiri::XML::Builder
        def entity(code)
          doc = Nokogiri::XML("&##{code};")
          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

    
    I can has • entity?
    

     

    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.

提交回复
热议问题