Html Attribute Encode - CSharp System

CSharp examples for System:String HTML

Description

Html Attribute Encode

Demo Code

// Permission is hereby granted, free of charge, to any person obtaining
using System.Text;
using System.Linq;
using System.Globalization;
using System.Collections.Generic;

public class Main{
        internal static string HtmlAttributeEncode (string s) 
      {//  www  .jav  a 2 s  .co  m
         if (s == null) 
            return null;
         
         if (s.Length == 0)
            return String.Empty;
         bool needEncode = s.Any(c => c == '&' || c == '"' || c == '<');

         if (!needEncode)
            return s;

         StringBuilder output = new StringBuilder ();
         int len = s.Length;
         for (int i = 0; i < len; i++)
            switch (s [i]) {
            case '&' : 
               output.Append ("&amp;");
               break;
            case '"' :
               output.Append ("&quot;");
               break;
            case '<':
               output.Append ("&lt;");
               break;
            default:
               output.Append (s [i]);
               break;
            }
   
         return output.ToString();
      }
}

Related Tutorials