Traverse XML Elements/Values with XmlDocument in C#

I’m in the process of writing a C# program that will validate field sizes (and maybe data types) against a SQL table. I need to traverse through each element and get the element value, the next step will be to validate it each element value.

The code below will “walk the tree” structure of the XML. Attributes are ignored in this program. The variable “indent” is used to indent each level of the XML as it is being processed. This program has a method TraverXmlNode that recursively calls itself to read the XML through unlimited levels of depth.

<pre>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace FieldSizeChecker 
{
    class Program
    {
        static void Main(string[] args)
        {
            string xmlFilename = "CanonicalSample1.xml";
            Console.WriteLine("\n\nStart XML Parser");
            ValidateXMLFieldValues(xmlFilename, objTable); 

            Console.WriteLine("\n\nPress enter to continue:");
            Console.ReadLine(); 

        }

        static void ValidateXMLFieldValues(string xmlFilename, SQLParserLibrary.Table objTable)
        {
            XmlDocument xmlDoc = new XmlDocument(); 
            xmlDoc.Load(xmlFilename);
            int depth = 0; 
            TraverseXMLNode(xmlDoc.DocumentElement, depth); 
        }

        
        static void TraverseXMLNode(XmlNode xmlNode, int depth)
        {
            //Loop through results
            depth = depth + 1;
            string indent = new String(' ', depth);
            if (xmlNode.NodeType == XmlNodeType.Element)
            {
                XmlElement element = (XmlElement)xmlNode;
                Console.WriteLine(indent + " elementName=" + element.Name + " Value=" + getElementTextValue(element))
                    ;
            }

            foreach (XmlNode childNode in xmlNode.ChildNodes)
            {
                TraverseXMLNode(childNode, depth);
            }

        }

        static string getElementTextValue(XmlElement element)
        {
            XmlNode firstChildNode = element.FirstChild; 
            if (firstChildNode != null)
            {
                return firstChildNode.Value;
            }
            else
            {
                return ""; 
            }
        }

    }

}
</pre>

Uncategorized  

Leave a Reply