Eric Bergman-Terrell's Blog

.NET Programming Tip: How to Encode XML Strings
September 4, 2010

If you have an XML string with characters such as ampersands that must be encoded, a method in the System.Security namespace will do the job. System.Security.SecurityElement.Escape("\"Eric\" &\'") returns ""Eric" & <Wilma>'".

Of course you could write your own method to encode <, >, ", ', and &, but this is the sort of thing the platform should do for you. It's puzzling that this method is not in the System.Xml namespace.

public static string XmlEncode()
{
  var text = "\"Eric\" & \'";

  return System.Security.SecurityElement.Escape(text);
}
Keywords: XML, Encoding, Ampersand, Escape, <, >, ', &quot, System.Security.SecurityElement, System.Xml

Reader Comments

Comment on this Blog Post

Recent Posts

TitleDate
EBTCalc Users: A Desktop Version is Now Available!October 25, 2019
Python Script to Audit MediaMonkey TranscodingAugust 15, 2019
How to decompile Java code with JetBrains IntelliJ IDEA (2018.2.3, Windows 10)October 5, 2018
Java Programming Tip: SWT Photo Frame ProgramOctober 31, 2016
Vault 3 (Desktop) Version 1.63 ReleasedSeptember 9, 2016
"Compliance with Court Orders Act of 2016"April 9, 2016
Disable "Visual Voicemail" on Android / T-MobileJanuary 17, 2016