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
.NET Public-Key (Asymmetric) Cryptography DemoJuly 20, 2025
Raspberry Pi 3B+ Photo FrameJune 17, 2025
EBTCalc (Android) Version 1.53 is now availableMay 19, 2024
Vault 3 Security EnhancementsOctober 24, 2023
Vault 3 is now available for Apple OSX M2 Mac Computers!September 18, 2023
Vault (for Desktop) Version 0.77 ReleasedMarch 26, 2023
EBTCalc (Android) Version 1.44 is now availableOctober 12, 2021