私は以下のようなエンティティを持っています
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; }
}
以下のように入力されます
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" });
そこから次のxmlを生成する必要があります
<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>
XDocument を使用してこれを行うにはどうすればよいですか?
私の失敗ショット
var res = (from x in lstDBDetails
group x by x.ServerId into g
select new
{
A = g.Key ,
B = g.ToList()
});
var doc = new XDocument(
new XElement("DataBaseServers",
res.Select(x =>
new XElement("DataBaseServer",
new XAttribute("id", x.A),
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))))))));