Create XML Tags to Return Web Service Response in XML Format

We can create well formed xml tags with the help of xElement. Its better way to create xml response instead of static defined tags in string varible or append in to string builder.
Create xml tags in C#.

First add namespaces for using xElement
 
using System.Xml.Linq;
  1. string cust_name = "Jack", cust_contactno = "12345678", cust_location = "India", cust_zipcode = "12345";  
  2. XElement obj;  
  3. obj = new XElement("start"new XElement("name", cust_name),  
  4. new XElement("contact", cust_contactno), new XElement("location", cust_location),  
  5. new XElement("zipcode", cust_zipcode)); 
  6. return obj.ToString();
Output
  1. <start>  
  2. <name>Jack</name>  
  3. <contact>12345678</contact>  
  4. <location>India</location>  
  5. <zipcode>12345</zipcode>  
  6. </start>  
Obj : Obj is the object of xelement .
 
New XElement("start":  Start is the root tag of this xml <start> will contain tags like name , location etc .you have to take one starting or root tag to acheive xml format . after the start tag all the tags are nest of it .
 
Output
  1. <start>  
  2.    <name>Jack</name>  
  3.    <contact>12345678</contact>  
  4.    <location>India</location>  
  5.    <zipcode>12345</zipcode>  
  6. </start>