TransWikia.com

XMLRead all same Notes

Stack Overflow Asked by ddave on November 29, 2021

Hi i have following xml file

<?xml version="1.0"?>
<Company>
     <Employee Name="Felix" Adress="Adress" age="22"> 
     <Employee Name="Felix" Adress="Adress" age="22"> 
     <Employee Name="Felix" Adress="Adress" age="22"> 
     <Employee Name="Felix" Adress="Adress" age="22"> 
     <Employee Name="Felix" Adress="Adress" age="22"> 
     <Employee Name="Felix" Adress="Adress" age="22"> 
     <Employee Name="Felix" Adress="Adress" age="22"> 
     <Employee Name="Felix" Adress="Adress" age="22"> 
     <Employee Name="Felix" Adress="Adress" age="22"> 
</Company>

I want to read it and get all names as an List. All Adress also as an List. All Ages also as an seperate List.
I have tried it with XDocument but i didnt figure it out how this should work.
I never know how long the list ist.
If I just get the whole string "<Employee Name="Felix" Adress="Adress" age="22"> " as one Listobject then i would just use a seperator but this not right to me.
I know there should be something to get a Attribut from a Node?
Thanks in advance
I want to build it in C#.
Linq is welcome

2 Answers

Try following :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:temptest.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            List<Employee> employee = doc.Descendants("Employee").Select(x => new Employee()
            {
                name = (string)x.Attribute("Name"),
                address = (string)x.Attribute("Adress"),
                age = (int)x.Attribute("age")
            }).ToList();

            List<string> names = employee.Select(x => x.name).ToList();
            List<string> addresses = employee.Select(x => x.address).ToList();
            List<int> ages = employee.Select(x => x.age).ToList();
        }
    }
    public class Employee
    {
        public string name { get; set; }
        public string address { get; set; }
        public int age { get; set; }
    }
}

Answered by jdweng on November 29, 2021

  • create a class Employee with properties Name, Address, Age
  • create a class Company with List of employees
  • deserialize your xml document into a Company
  • access the list of employees and their properties from the deserialized company

Answered by Z.D. on November 29, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP