magritton
12/18/2015 - 2:46 PM

C# recursivly go through all the nodes in an XML document. There is also a tag for the parent.

C# recursivly go through all the nodes in an XML document. There is also a tag for the parent.

static void Main(string[] args)
        {
            XmlDocument document = new XmlDocument();
            document.Load(@"C:\Xml\cc\ccx.xml");
            RecurseXmlDocument((XmlNode)document.DocumentElement, "TopNode");
            Console.WriteLine("Press any Key....");
            Console.ReadKey(false);
        }

        private static void RecurseXmlDocument(XmlNode root, string strParent)
        {
            if (root is XmlElement)
            {
                Console.WriteLine(root.Name + " Parent: " + strParent );
                if (root.HasChildNodes)
                    RecurseXmlDocument(root.FirstChild, root.Name);
                if (root.NextSibling != null)
                    RecurseXmlDocument(root.NextSibling, strParent);
            }
            else if (root is XmlText)
            {
                string text = ((XmlText)root).Value;
                Console.WriteLine(text);
            }
            //else if (root is XmlComment)
            //{
            //    string text = root.Value;
            //    Console.WriteLine(text);
            //    if (root.HasChildNodes)
            //        RecurseXmlDocument(root.FirstChild, indent + 2);
            //    if (root.NextSibling != null)
            //        RecurseXmlDocument(root.NextSibling, indent);
            //}
        }