TechyMedia

A .NET Technology blog | .NET,C# Progamming,C# tutorials,WPF WCF|Software Engineer

NAVIGATION - SEARCH

C# .NET- How To Read CDATA Section

Article explains how to Extract cdata from xml. CDATA (Character Data) is used to store information in XML file as unparsable data so that no parser will parse it and will be treated as pure char string. In this article I am explaining how to read the data stored as CDATA section in an XML file using XmlDocument in C# .NET.

CDATA (Character Data) as discussed in my previous articles  is used to store information in XML file as unparsable data so that no parser will parse it and will be treated as pure char string. In this article I am  explaining  how to read  the data stored as CDATA section in  an XML file using XmlDocument in  C# .NET.

C++ Ultimate Video Training - Best Course Ever icon

Here is an  XML file  which stores some java script blocks in CDATA section under script tag.

<?xmlversion="1.0"encoding="utf-8" ?>
<Root>
<script>
   <![CDATA[
      function FindHigher(var1,var2,var3)
      {
        if (var1 > var2 && var1 > var2) then
        {
          return var1;
        }
        if(var2 > var1 && var2 > var3) then
        {
          return var2;
        }

        if(var3 > var1 && var3 > var2) then
        {
          return var3;
        }
        else
        {
          return 0;
        }   
     }
  ]]>
</script>

<script>
   <![CDATA[
      function FindHigher(val1,val2)
      { 
          return val1 + val2;
       }
  ]]>
</script>
</Root>

Extract xml cdata section 

Here below a utility method which parse the XML file and returns a List of all CDATA under script elements.

publicstaticList<string> GetCdataSectionValues(string xmlFilePath,string elementNode)
{
            List<string> lstCdataValues = newList<string>();

            XmlDocument doc = newXmlDocument();

            doc.Load(xmlFilePath);         

            XmlNodeList parentNodes = doc.DocumentElement.SelectNodes(elementNode);

            foreach (XmlNode parentNode in parentNodes)

            {

                XmlNode cDataNode = parentNode.ChildNodes[0];

                if (cDataNode isXmlCDataSection)

                {

                    XmlCDataSection cdataSection = cDataNode asXmlCDataSection;

                    lstCdataValues.Add(cdataSection.Value);

                }

            }

            return lstCdataValues;
 }

 

Test the output:

List<string> cDataList = QueryHandler.GetCdataSectionValues(@"E:\XmlSample.xml", @"//Root/script");

  foreach (string cDataValue in cDataList)
  {
      MessageBox.Show(cDataValue);
  }

 

Efficient XML Parsing Techniques in .NET

Comments (2) -

Jacqui Mccarrol
United States Jacqui Mccarrol

Great website, really enjoyed it.

Reply

How do you delete your blog comment that you left on someone else blog?

Reply

Pingbacks and trackbacks (1)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading