Saturday, June 5, 2010

How to Read an XML File in C#

XML is a helpful format when you want to load configuration files, and read dynamic data from a static file. This code reads form a simple XML file, with various nodes. There are a few different ways to do this, but this is the easiest, XMLDocument. 



public void ReadConfigXML()
        {
            XmlDocument doc = new XmlDocument();
          
            doc.Load(Directory.GetCurrentDirectory().
                ToString() +
                @"\config.xml");
            XmlNodeList nodes = doc.SelectNodes(
                "/xml/ext/@* | /xml/ext/text()");
            foreach (XmlNode node in nodes)
            {
                comboBox1.Items.Add(node.Value);
            }

            nodes = doc.SelectNodes(
                "/xml/title/@* | /xml/title/text()");
            foreach (XmlNode node in nodes)
            {
                appTitle = node.Value;
            }

            nodes = doc.SelectNodes(
                "/xml/daysold/@* | /xml/daysold/text()");
            foreach (XmlNode node in nodes)
            {
                txtDaysOld.Value =
                    Convert.ToInt32(node.Value.ToString());
            }

            nodes = doc.SelectNodes(
                "/xml/path/@* | /xml/path/text()");
            foreach (XmlNode node in nodes)
            {
                txtFileName.Text = node.Value;
            }

            nodes = doc.SelectNodes(
                "/xml/logfile/@* | /xml/logfile/text()");
            foreach (XmlNode node in nodes)
            {
                LogFile = Directory.GetCurrentDirectory().
                    ToString()  +  @"\" + node.Value;
            }
        }

No comments:

Post a Comment

Generating "Always On Top" NSWindow in macOS across all detected displays

Also: Using UIKit & Cocoa Frameworks using Objective-C In m acOS or OS X , written in either Objective-C or Swift  Langues, you m...