I have below xml file
<Department Name="Electronic">
<Employee ID="1" Name="John" Address="xyz,abc" />
<Employee ID="2" Name="Jim" Address="ntg,abc"/>
<Employee ID="3" Name="Liz" Address="rhx,abc" />
</Department>
<Department Name="Computer">
<Employee ID="1" Name="Tony" Address="mnc,abc"" />
<Employee ID="2" Name="Tom" Address="abr,abc" />
</Department>
I want to get data in this form using C# and linq
Electronic, 1 , John
Electronic, 2 , Jim
Electronic, 3 , Liz
Computer,1,Tony
Computer,2,Tom
Currently i am only getting ID and Name with below query, but i want to get department name as well
1 , John
2 , Jim
3 , Liz
1,Tony
2,Tom
var result1 = str.Elements("Department").Elements("Employee")
.Select(node => new
{
ID = node.Attribute("ID").Value,
Name = node.Attribute("Name").Value,
}
).ToList();
CodePudding user response:
public class Employee
{
public string Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Department { get; set; }
}
//Replace doc with your xml element
XElement doc = XElement.Parse(File.ReadAllText("XmlFilePath"));
var employeeList = doc.Elements("Department").Elements("Employee")
.Select(node => new Employee
{
Id = node.Attribute("ID")?.Value,
Name = node.Attribute("Name")?.Value,
Address = node.Attribute("Address")?.Value,
Department = node.Parent?.Attribute("Name")?.Value,
}).ToList();
CodePudding user response:
Try following which give the output you are looking for
using System;
using System.Linq;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;
using System.IO;
namespace ConsoleApp2
{
class Program
{
const string INPUT_FILENAME = @"c:\temp\test.xml";
const string OUTPUT_FILENAME = @"c:\temp\test.csv";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(INPUT_FILENAME);
StreamWriter writer = new StreamWriter(OUTPUT_FILENAME);
foreach(XElement department in doc.Descendants("Department"))
{
string departmentName = (string)department.Attribute("Name");
foreach(XElement employee in department.Elements("Employee"))
{
string id = (string)employee.Attribute("ID");
string employeeName = (string)employee.Attribute("Name");
string line = string.Join(",", new string[] { departmentName, id, employeeName });
writer.WriteLine(line);
}
}
writer.Flush();
writer.Close();
}
}
}