def purify(untrusted)
      # First pass: strip bad UTF-8 characters
      if RUBY_VERSION =~ /^1\.8/
        iconv = Iconv.new('UTF-8//IGNORE', 'UTF-8')
        result = iconv.iconv(untrusted)
      else
        result = untrusted.force_encoding(Encoding::BINARY).encode('UTF-8', :undef=>:replace, :replace=>'')
      end

      # Second pass: entity escape characters that can't appear in XML CDATA.
      result.gsub(INVALID_CDATA_CHARACTER) do |ch|
        "&#x%s;" % [ch.unpack('H*').first]
      end
    end
def purify(untrusted)
      # First pass: strip bad UTF-8 characters
      if RUBY_VERSION =~ /^1\.8/
        iconv = Iconv.new('UTF-8//IGNORE', 'UTF-8')
        result = iconv.iconv(untrusted)
      else
        result = untrusted.force_encoding(Encoding::BINARY).encode('UTF-8', :undef=>:replace, :replace=>'')
      end

      # Second pass: entity escape characters that can't appear in XML CDATA.
      result.gsub(INVALID_CDATA_CHARACTER) do |ch|
        "&#x%s;" % [ch.unpack('H*').first]
      end
    end
Strip invalid UTF-8 sequences from a string and entity-escape any character that can't legally
 appear inside XML CDATA. If test output contains weird data, we could end up generating
 invalid JUnit XML which will choke Java. Preserve the purity of essence of our precious XML
 fluids!

 @return [String] the input with all invalid UTF-8 replaced by the empty string
 @param [String] untrusted a string (of any encoding) that might contain invalid UTF-8 sequences