.NET Framework Class Library
SecurityElement.Escape Method

Replaces invalid XML characters in a string with their valid XML equivalent.

Namespace: System.Security
Assembly: mscorlib (in mscorlib.dll)

Syntax

Visual Basic (Declaration)
Public Shared Function Escape ( _
    str As String _
) As String
Visual Basic (Usage)
Dim str As String
Dim returnValue As String

returnValue = SecurityElement.Escape(str)
C#
public static string Escape (
    string str
)
C++
public:
static String^ Escape (
    String^ str
)
J#
public static String Escape (
    String str
)
JScript
public static function Escape (
    str : String
) : String

Parameters

str

The string within which to escape invalid characters.

Return Value

The input string with invalid characters replaced.
Remarks

Use this method to replace invalid characters in a string before using the string in a SecurityElement. If invalid characters are used in a SecurityElement without being escaped, an ArgumentException is thrown.

The following table shows the invalid XML characters and their escaped equivalents.

invalid XML Character

Replaced With

"<"

"&lt;"

">"

"&gt;"

"\""

"&quot;"

"\'"

"&apos;"

"&"

"&amp;"

Example

The following code shows the use of the Escape method to replace invalid XML characters in a string with their valid XML equivalent. This code example is part of a larger example provided for the SecurityElement class.

Visual Basic
tagText = SecurityElement.Escape(tagText)
C#
tagText = SecurityElement.Escape(tagText);
C++
tagText = SecurityElement::Escape( tagText );
J#
tagText = SecurityElement.Escape(tagText);
Platforms

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

Version Information

.NET Framework

Supported in: 2.0, 1.1, 1.0
See Also

Tags :


Community Content

woezelmann
other invalid characters
what's about "/" ?? it's also invalid
Tags : contentbug

Thomas Lee
other invalid characters

also:

  • @
  • [
  • ]
  • "whitespace"

...and a multitude of others...these 5 are helpful but I could just as easily use a switch statement to escape those 5. perhaps a more comprehensive method could be provided....

Tags : contentbug

blairdev
This class will remove invalid characters from UTF-8 encoded XML documents
using System;
using System.IO;
using System.Security;
using System.Xml;

namespace ReadXMLSalesDataAPI
{
public class PreProcessXML// : IPreProcessXML
{
private string xmlFilename;

/// <param name="_xmlFilename">The filename of the XML document to be converted.</param>
public PreProcessXML(string _xmlFilename)
{
xmlFilename = _xmlFilename;
}

/// <summary>Read the XML file.</summary>
public void ConvertXMLDocument(long linenumber, int lineposition, string exception)
{
try
{
string filepath = xmlFilename;

StreamReader strm;
string strline;
string tempfile = "C:\\Temp.xml";//temporay XML document, for reading from

try
{
File.Copy(filepath, tempfile, true);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}

StreamWriter strmwriter = new StreamWriter(filepath);
strmwriter.AutoFlush = true;
strm = new StreamReader(tempfile);
int i = 0;

//get the first part of the XML document, upto the invalid character
string line = "";
string errorLine = "";
while ((line = strm.ReadLine()) != null)
{
//get a string containing the correct line
if (i == (linenumber - 1))
{
errorLine = line;
Console.WriteLine("Line num " + i + ", where invalid character is: " + errorLine);
break;
}
else
{
strline = line;
strmwriter.WriteLine(strline);
}

i++;
}
strm.Close();

//check that an invalid characters such as '£' pound sign has not been found
if (!exception.Contains("Invalid character in the given encoding"))
{
//next get the correct line position, which is to be replaced with an XML safe equivalent
string strToReplace = errorLine.Substring(lineposition - 2, 1);
//Console.WriteLine("Char to replace is: " + strToReplace);

//line with the valid character replaced
string newLine = errorLine.Substring(0, lineposition - 2);
// Console.WriteLine("First part is: " + newLine);

//check that a pound sign has not been found
if (SecurityElement.Escape(strToReplace).Trim() != string.Empty)
{
newLine += SecurityElement.Escape(strToReplace);
}
else
{
newLine += strToReplace;
}

//Console.WriteLine("Escape character added is: " + SecurityElement.Escape(strToReplace));
newLine += errorLine.Substring(lineposition - 1);
//Console.WriteLine("Finally Converted line is: " + newLine);

strmwriter.WriteLine(newLine);

strToReplace = SecurityElement.Escape(strToReplace);

//Console.WriteLine("After Conversion, Char to replace with is: " + strToReplace);
}
else
{
strmwriter.WriteLine(errorLine);
}

line = "";
strm = new StreamReader(tempfile);
i = 0;

//get the rest of the XML document after the XML character
while ((line = strm.ReadLine()) != null)
{
//get the rest of the document
if (i >= linenumber)
{
strline = line;
strmwriter.WriteLine(strline);
}

i++;
}

strm.Close();
strm = null;

strmwriter.Flush();
strmwriter.Close();
strmwriter = null;

//finally delete the temporary XML file to free resources, as it is finished with
File.Delete(tempfile);
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
}

/// <summary>Attempt to load the XML document. This will determine if the document,
/// contains any errors or not.</summary>
public XmlDocument LoadXMLDoc()
{
XmlDocument xdoc;
int lineNum;
int linePos;

xdoc = new XmlDocument();

try
{
xdoc.Load(xmlFilename);
}
catch (XmlException ex)
{
Console.WriteLine("Exception: " + ex.Message);
lineNum = ex.LineNumber;
linePos = ex.LinePosition;

if (lineNum != 0)
{
if (linePos != 0)
{
ConvertXMLDocument(lineNum, linePos, ex.Message);

LoadXMLDoc();
}
}
}

return (xdoc);
}
}
}

Page view tracker