
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Handling Invalid Characters in an XML String
|
851
The second way is to let the XmlElement class escape the data for you by assigning the
text directly to the
InnerText property like this:
// Set up a string with our invalid chars.
string invalidChars = @"<>\&'";
XmlElement invalidElement2 = xmlDoc.CreateElement("InvalidChars2");
invalidElement2.InnerText = invalidChars;
The whole XmlDocument is created with these XmlElements in this code:
public static void HandlingInvalidChars( )
{
// Set up a string with our invalid chars.
string invalidChars = @"<>\&'";
XmlDocument xmlDoc = new XmlDocument( );
// Create a root node for the document.
XmlElement root = xmlDoc.CreateElement("Root");
xmlDoc.AppendChild(root);
// Create the first invalid character node.
XmlElement invalidElement1 = xmlDoc.CreateElement("InvalidChars1");
// Wrap the invalid chars in a CDATA section and use the
// InnerXML property to assign the value as it doesn't
// escape the values, just passes in the text provided.
invalidElement1.InnerXml = "<![CDATA[" + invalidChars + "]]>";
// Append the element to the root node.
root.AppendChild(invalidElement1);
// Create the second invalid character node.
XmlElement invalidElement2 = xmlDoc.CreateElement("InvalidChars2");
// Add the invalid chars directly using the InnerText ...