I am trying to convert a list of objects into xml using XElement. My code is as below
var employees = new List<Employee>();
employees.Add(new Employee("1", " Ali","",1000));
employees.Add(new Employee("2", "Billy","",1001));
var xml = new XElement("root");
xml.Add(new XElement("Employees"));
foreach (var employee in employees)
{
xml.Add(new XElement("employee", employee.Name));
};
I want an output like this
<root>
<Employees>
<employee>Ali</employee>
<employee>Billy</employee>
</Employees>
</root>
but the output I m getting is
<root>
<Employees/>
<employee>Ali</employee>
<employee>Billy</employee>
</root>
I tried moving the Employees object inside the loop like below but that does not help either
foreach (var employee in employees)
{
xml.Add(new XElement("Employees", new XElement("employee", employee.Name)));
};
Within your loop, you should call Add()
on your employees element rather than on your root:
var employees = new List<Employee>();
employees.Add(new Employee("1", " Ali","",1000));
employees.Add(new Employee("2", "Billy","",1001));
var xml = new XElement("root");
var employeesElement = new XElement("Employees");
foreach (var employee in employees)
{
employeesElement.Add(new XElement("employee", employee.Name));
}
xml.Add(employeesElement);
XElement
constructor can handle IEnumerable
so you can add employee
elements at once while creating the parent Employees
. In fact, the entire XML can be created at once :
var xml = new XElement("root",
new XElement("Employees",
employees.Select(e => new XElement("employee", e.Name))
)
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.