Friday, 29 July 2011

Generating xml using linq query

The sample code for generating xml using linq query as follows
List<Contact> contacts = Contact.SampleData();
List<CallLog> callLog = CallLog.SampleData();
var q = from call in callLog
where call.Incoming == true
group call by call.Number into g
join contact in contacts on
g.Key equals contact.Phone
orderby contact.LastName, contact.FirstName
select new XElement(”contact”,
new XElement(”lastName”,
contact.LastName),
new XElement(”firstName”,
contact.FirstName),
new XElement(”count”,
g.Count()),
new XElement(”totalDuration”,
g.Sum(c => c.Duration)),
new XElement(”averageDuration”,
g.Average(c => c.Duration))
);
// create the XML document and add the items in query q
XDocument doc = new XDocument(
new XComment(”Summarized Incoming Call Stats”),
new XElement(”contacts”, q)
);
Console.WriteLine(doc.ToString());

output for the above query is as follows
<!—Summarized Incoming Call Stats—> 
<contacts>
<contact> 
<lastName>Gottshall</lastName> 
<firstName>Barney</firstName> 
<count>4</count> 
<totalDuration>31</totalDuration> 
<averageDuration>7.75</averageDuration>
</contact> 
... (records cut for brevity) 
<contact>
<lastName>Valdes</lastName> 
<firstName>Armando</firstName> 
<count>2</count> 
<totalDuration>20</totalDuration> 
<averageDuration>10</averageDuration>
</contact> 
</contacts>

No comments:

Post a Comment