public string InsertCDATASections(DataSet ds, string[] cdataSections)
{
XmlValidatingReader reader = null;
XmlTextWriter writer = null;
StringWriter sw = null;
Array.Sort(cdataSections);
try
{
reader = new XmlValidatingReader(ds.GetXml(), XmlNodeType.Document, null);
sw = new StringWriter();
writer = new XmlTextWriter(sw);
writer.Formatting = Formatting.Indented;
reader.ValidationType = ValidationType.None;
reader.EntityHandling = EntityHandling.ExpandCharEntities;
string currentElement = String.Empty;
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
currentElement = reader.Name;
writer.WriteStartElement(currentElement);
while (reader.MoveToNextAttribute())
{
writer.WriteAttributeString(reader.Name, reader.Value);
}
break;
case XmlNodeType.Text:
if (Array.BinarySearch(cdataSections, currentElement) < 0 && cdataSections.Length > 0 )
{
writer.WriteString(reader.Value);
}
else
{
writer.WriteCData(reader.Value);
}
break;
case XmlNodeType.EndElement:
writer.WriteEndElement();
break;
default:
break;
}
}
}
catch (Exception exp)
{
return exp.Message;
}
finally
{
reader.Close();
writer.Close();
}
return sw.ToString();
}
Example:
DataSet ds = new DataSet();
string[] sections = new string[]{};
string xml = InsertCDataSections(ds, sections);