Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

17.7. Handling Invalid Characters in anXML String

Problem

You are creating an XML string. Before adding a tag containing a text element, you want to check it to determine whether the string contains any of the following invalid characters:

<
>
\"
\'
&

If any of these characters are encountered, you want them to be replaced with their escaped form:

&lt;
&gt;
&quot;
&apos;
&amp;

Solution

There are different methods to accomplish this, depending on which XML creation approach you are using. If you are using XmlTextWriter, the WriteCData and WriteElementString methods take care of this for you. If you are using XmlDocument and XmlElements, the XmlElement.InnerXML and XmlElement.InnerText methods will handle these characters.

The two ways to handle this using an XmlTextWriter work like this. The WriteCData method will wrap the invalid character text in a CDATA section, as shown in the creation of the InvalidChars1 element in the example that follows. The other method, using XmlTextWriter, 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 = @"<>\&'"; XmlTextWriter writer = new XmlTextWriter(Console.Out); writer.WriteStartElement("Root"); writer.WriteStartElement("InvalidChars1"); writer.WriteCData(invalidChars); writer.WriteEndElement( ); writer.WriteElementString("InvalidChars2",invalidChars); writer.WriteEndElement( ); writer.Close( ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata