
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
850
|
Chapter 15: XML
If any of these characters are encountered, you want them to be replaced with their
escaped form:
<
>
"
'
&
Solution
There are different ways to accomplish this, depending on which XML-creation
approach you are using. If you are using XmlWriter, the WriteCData, WriteString,
WriteAttributeString, WriteValue, and WriteElementString methods take care of this
for you. If you are using
XmlDocument and XmlElements, the XmlElement.InnerText
method will handle these characters.
The two ways to handle this using an
XmlWriter work like this. The WriteCData
method will wrap the invalid character text in a CDATA section, as shown in the cre-
ation of the
InvalidChars1 element in the example that follows. The other method,
using
XmlWriter, is to use the WriteElementString method that will automatically
escape the text for you, as shown while creating the
InvalidChars2 element.
// Set up a string with our invalid chars.
string invalidChars = @"<>\&'";
XmlWriterSettings settings = new XmlWriterSettings( );
settings.Indent = true;
using (XmlWriter writer = XmlWriter.Create(Console.Out, settings))
{
writer.WriteStartElement("Root");
writer.WriteStartElement("InvalidChars1");
writer.WriteCData(invalidChars);
writer.WriteEndElement( );
writer.WriteElementString("InvalidChars2", ...