Thursday, August 22, 2013

Add CData Section to existing xml string in C#

public class Example
    {
        static void Main(string[] args)
        {
           //Create the xml in the XmlDocument
            XmlDocument dom = new XmlDocument();
            //Root of xml
            XmlElement root = dom.CreateElement("root");
            //Sub nodes
            XmlElement id = dom.CreateElement("id");
            id.InnerText = "1";
            XmlElement name = dom.CreateElement("name");
            XmlCDataSection cdata = dom.CreateCDataSection("<test>");
            name.AppendChild(cdata);
            root.AppendChild(id);
            root.AppendChild(name);
            dom.AppendChild(root);
          
            //Output to the StringBuilder
            StringBuilder sbu = new StringBuilder();
            StringWriter sw = new StringWriter(sbu);
            XmlTextWriter writer = new XmlTextWriter(sw);
            writer.Formatting = Formatting.Indented;
            dom.WriteTo(writer);
            //Output this xml
            Console.WriteLine(sbu.ToString());

            //Read this xml string out
            XmlDocument doc2 = new XmlDocument();
            doc2.LoadXml(sbu.ToString());
        }
     }

No comments:

Post a Comment

Opps Part 1 : Abstraction

  Abstraction in C# is a fundamental concept of object-oriented programming (OOP) that allows developers t...