C#: Adding CData Sections to an Existing Node using XmlDocument and XDocument to handle HTML code or other problematic characters

Posted by OmegaMan at July 14, 2009

Category: XML

Tags: , ,

There are situations where the data within nodes of Xml need to be handled due to special characters or html type tags. To handle that one must place data into CData sections. This artcle shows one how to do that in .Net using C# for both the XMLDocument as well as the XDocument.

XMLDocument Example

string myXml =
@"<?xml version='1.0' encoding='utf-8'?>
<WorkingSet>
 <Data>
 </Data>
</WorkingSet>";

XmlDocument doc1 = new XmlDocument();
doc1.LoadXml( myXml );

XmlNode target = doc1.SelectSingleNode( "WorkingSet/Data" );

if (target != null)
    target.AppendChild( doc1.CreateCDataSection( "<h1>Hello</h1>" ) );

XDocument Example

XDocument doc = XDocument.Parse( myXml, LoadOptions.SetLineInfo );

XElement dataNode = doc.Descendants( "Data" ).First();

dataNode.Add ( new XCData( "<h1>Hello</h1>" ));

Console.WriteLine( doc.ToString() );

Results

<?xml version="1.0" encoding="utf-8"?>
<WorkingSet>
 <Data><![CDATA[<h1>Hello</h1>]]></Data>
</WorkingSet>
Share

4 Comments

  1. Abdul Rahman says

    nice work, really helpful, thanks.

    Reply
  2. Schlüsselnotdienst Duisburg says

    Duisburg Schlüssel…

    […]C#: Adding CData Sections to an Existing Node using XmlDocument and XDocument to handle HTML code or other problematic characters « OmegaMan's Musings[…]…

    Reply
  3. Manuel Guillen says

    Hi. How can I include a cdata section in a asp.net web service response?? I need to include text info with ampersand character. Thanks in advance.

    Reply
  4. Jason S says

    Great post. I am wondering if you know of a clever way to wrap one or more instances of special characters with CDATA?

    Example:
    Hey look at this annoying <![CDATA[ in the middle of my string

    Reply

Leave a comment

(required)
(required) (will not be published)

This site uses Akismet to reduce spam. Learn how your comment data is processed.