Reading Xml Document with Load Method

Step1

Open Notepad Copy the following code and save in C:\CSharpExs folder as LinesofBusiness.xml. Then the file path will be "C:\CSharpExs\LinesofBusiness.xml"

<?xml version="1.0" encoding="utf-8" ?>
<CTSLOB>
  <LOB>
    <Name>BFS</Name>
  </LOB>
  <LOB isActive="true">
    <Name>Healthcare</Name>
  </LOB>
  <LOB isActive="true">
    <Name>Insurance</Name>
  </LOB>

</CTSLOB>

Step2

In visual studio, create a project with the following code, and run it.


using System;

//Added...
using System.Xml;

namespace IO_Samples
{
    class ReadXMLDocument
    {
        static string FilePath = @"C:\CSharpExs\LinesofBusiness.xml";
        static void Main(String[] xyz)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(FilePath);

            XmlNodeList xmlnode = doc.GetElementsByTagName("LOB");
            for (int i = 0; i <= xmlnode.Count - 1; i++)
            {
               Console.WriteLine(xmlnode[i].ChildNodes.Item(0)
                                             .InnerText.Trim());
            }
            Console.ReadKey();
        }
    }
}

Output

BFS
Healthcare
Insurance

No comments:

Post a Comment