Monday, July 12, 2010

Replace Illegal XML Characters - C#

The following method replaces characters illegal in XML with their appropriate substitutes.

        /// 
        /// Removes illegal characters in an XML file with appropriate replacements
        /// 
        /// xml line        /// line with replacements made
        public string replaceIllegalChars(string line)
        {
            System.Text.Encoding utf8 = System.Text.Encoding.UTF8;

            byte[] utf8bytes = System.Text.Encoding.UTF8.GetBytes(line);

            line = System.Text.Encoding.UTF8.GetString(utf8bytes);

            line = line.Replace("&", "&");
            line = line.Replace("<", "<");
            line = line.Replace("\"", """);
            line = line.Replace("\'", "'");
            line = line.Replace(">", ">");


            return line;

        }

1 comments:

Arsalan said...

good job....

Post a Comment