Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate CDATA with XmlTextWriter?

Tags:

c#

.net

xml

I'm using XmlTextWriter class in my project. i don't know, how to use CDATA in Xml. Can anyone help me?

objX.WriteElementString("category", c.DeepestCategoryName);
like image 993
ozkank Avatar asked Dec 21 '22 19:12

ozkank


1 Answers

As noted by others, use WriteCData if you want to write a CDATA section explicitly. Here is a general-purpose extension method that I use to write a CDATA element 'automatically' if the text contains certain characters:

public static void WriteElementContent(this XmlWriter writer, string content)
{
    if (String.IsNullOrEmpty(content))
    {
        return;
    }

    // WriteString will happily escape any XML markup characters. However, 
    // for legibility we write content that contains certain special
    // characters as CDATA 
    const string SpecialChars = @"<>&";
    if (content.IndexOfAny(SpecialChars.ToCharArray()) != -1)
    {
        writer.WriteCData(content);
    }
    else
    {
        writer.WriteString(content);
    }
}
like image 140
Rich Tebb Avatar answered Jan 04 '23 22:01

Rich Tebb