Generate XML from Collection using XDocument

Niladri.Biswas
Posted by Niladri.Biswas under C# category on | Points: 40 | Views : 844
I have an entity as under

class DBDetails
{
public int ServerId { get; set; }
public string Title { get; set; }
public string Address { get; set; }
public int DBId { get; set; }
public string DbName { get; set; }
public string UserId { get; set; }
public string Password { get; set; }
}


It is populated as under

List<DBDetails> lstDBDetails = new List<DBDetails>();
lstDBDetails.Add(new DBDetails { ServerId = 1, Title = "IISDevdb1", Address = "Address1", DBId = 1, DbName = "db1", UserId = "u1", Password = "p1" });
lstDBDetails.Add(new DBDetails { ServerId = 2, Title = "iis2", Address = "Address2", DBId = 2, DbName = "db2", UserId = "u2", Password = "p2" });
lstDBDetails.Add(new DBDetails { ServerId = 1, Title = "IISDevdb1", Address = "Address1", DBId = 3, DbName = "db3", UserId = "u3", Password = "p3" });


I need to generate the following xml from it

<DataBaseServers>
<DataBaseServer id="1" title="IISDevdb1" address="Address1">
<DataBases>
<database id="1" name="db1" userID="u1" password="p1" />
<database id="3" name="db3" userID="u3" password="p3" />
</DataBases>
</DataBaseServer>
<DataBaseServer id="2" title="iis2" address="Address2">
<DataBases>
<database id="1" name="db2" userID="u2" password="p2" />
</DataBases>
</DataBaseServers>


How can I do so using XDocument?

Solution
var res = (from x in lstDBDetails
group x by new { x.ServerId, x.Title,x.Address } into g
select new
{
ServerId = g.Key.ServerId,
Title = g.Key.Title,
Address = g.Key.Address,
B = g.ToList()
});

var doc = new XDocument(
new XElement("DataBaseServers",
res.Select(x =>
new XElement("DataBaseServer",
new XAttribute("id", x.ServerId),
new XAttribute("title", x.Title),
new XAttribute("address", x.Address),
new XElement("DataBases",
x.B.Select(y =>
new XElement("database",
new XAttribute("id", y.DBId),
new XAttribute("name", y.DbName),
new XAttribute("userID", y.UserId),
new XAttribute("password", y.Password))))))));

Comments or Responses

Login to post response