1

I am new to C# asp.net coding so I am facing a bit problem. This is my xml file. I want to retrieve " < DOB > " values of each employee and want to store them in a list, say "emps_dob". Please help me with this. Thank u

<?xml version="1.0" encoding="utf-8"?>
<employees>
  <employee>
    <name> Vin </name>
    <DOB> 07/10 </DOB>
    <emailID> vinay@abc.com</emailID>
  </employee>
  <employee>
    <name> ben </name>
    <DOB> 08/11 </DOB>
    <emailID> ben@abc.com</emailID>
  </employee>
  <employee>
    <name> tin </name>
    <DOB> 09/12 </DOB>
    <emailID> tin@abc.com</emailID>
  </employee>

3 Answers3

5

You can use linq as per answer given in this post

var doc = XDocument.Load("yourfilepath")
var dobs= doc.Root.Elements().Select( x => x.Element("DOB") );


OR

using System;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main( string[] args )
        {
            XDocument doc = XDocument.Load( "XMLFile1.xml" );
            List<string> emps_dob=new List<string>();
            var dobs= doc.Descendants( "DOB" );

            foreach ( var item in dobs)
            {
                emps_dob.Add(item.Value);
            }

        }
    }
}
Community
  • 1
  • 1
Nilesh Gajare
  • 6,302
  • 3
  • 42
  • 73
1
XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString);  
XmlNodeList xnList = xml.SelectNodes("/employees/employee");
foreach (XmlNode xn in xnList)
{
  string name= xn["name"].InnerText;
  string DOB= xn["name"].InnerText;
  Console.WriteLine("Name: {0} {1}", name, DOB);
}
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
0
using System.Xml;

List<string> dob = new List<string>();
XmlDocument doc = new XmlDocument();
doc.Load("abc.xml");
XmlNode root = doc.DocumentElement;
foreach (XmlNode node1 in root.ChildNodes)
{
        foreach (XmlNode node2 in node1.ChildNodes)
        {
               if (node2.Name.ToString() == "DOB")
                dob.Add(node2.InnerText.ToString());
        }
}
Dheeraj Singh
  • 5,143
  • 25
  • 33