-2

Hello everybody I have a XML document like this one below:

<Users>
  <User>
    <Name>Aram</Name>
    <Lastname>Vardanyan</Lastname>
    <Email>*****@gmail.com</Email>
    <Phone>*** ******</Phone>
  </User>
</Users>

I need to get values of Name, Lastname, Email, Phone and put them in my console application. Thanks everyone.

  • 3
    Possible duplicate of [How do I read and parse an XML file in C#?](https://stackoverflow.com/questions/642293/how-do-i-read-and-parse-an-xml-file-in-c) – GSerg Jun 13 '20 at 09:29
  • Your question already exists, simple google search like "C# extracting data from XML" will give you an answer. – Jonathan Applebaum Jun 13 '20 at 09:29

1 Answers1

0

Try with this simple solution that uses XmlDocument to parse the XML document you provided. Note that this sample shows you just how to get the values you need, not how and from where you load the content that you want to parse.

using System;
using System.Collections.Generic;
using System.Xml;

public class User
{
    public string Name { get; set; }

    public string LastName { get; set; }

    public string Email { get; set; }

    public string Phone { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var xmlAsString = @"<Users>
          <User>
            <Name>Aram</Name>
            <Lastname>Vardanyan</Lastname>
            <Email>*****@gmail.com</Email>
            <Phone>*** ******</Phone>
          </User>
        </Users>";

        var xmlDocument = new XmlDocument();
        xmlDocument.LoadXml(xmlAsString);

        var users = new List<User>();
        foreach(XmlElement xmlUser in xmlDocument.DocumentElement.ChildNodes)
        {
            var user = new User()
            {
                Name = xmlUser["Name"].InnerText,
                LastName = xmlUser["Lastname"].InnerText,
                Email = xmlUser["Email"].InnerText,
                Phone = xmlUser["Phone"].InnerText
            };

            users.Add(user);
        }

        users.ForEach(u =>
        {
            Console.WriteLine(u.Name);
            Console.WriteLine(u.LastName);
            Console.WriteLine(u.Email);
            Console.WriteLine(u.Phone);
        });

        Console.ReadKey();
    }
}
claudiom248
  • 346
  • 2
  • 9