Convert Object to XML

Posted by Suneel161 under Regular Expressions on 6/20/2011 | Points: 10 | Views : 4133 | Status : [Member] | Replies : 2
Hi..

Convert object to xml in c#.net

like.
<?xml version="1.0" encoding="UTF-8" ?>
- <book_ticket>
- <seat_details>
- <seat_detail>
<seat_number>14</seat_number>
<title>Mr</title>
<name>Ravi</name>
<age>28</age>
<sex>M</sex>
<is_primary>true</is_primary>
</seat_detail>
- <seat_detail>
<seat_number>15</seat_number>
<title>Mrs</title>
<name>Kavi</name>
<age>24</age>
<sex>F</sex>
<is_primary>false</is_primary>
</seat_detail>
</seat_details>
- <contact_detail>
<email>ravi@gmail.com</email>
<mobile_number>9742282521</mobile_number>
<emergency_name>Kavi</emergency_name>
</contact_detail>
</book_ticket>




Responses

Posted by: Ndebata on: 6/20/2011 [Member] Starter | Points: 25

Up
0
Down
Hi lets say i have my class structure like this
public class Contact

{
public string email { get; set; }
public string mobile_number { get; set; }
public string emergency_name { get; set; }
}
public class Seat
{
public int seat_number { get; set; }
public string name { get; set; }
public int age { get; set; }
public bool is_primary { get; set; }
}
public class Ticket
{
public List<Seat> Seats;
public Contact Contact;
public Ticket()
{
Seats = new List<Seat>();
this.Contact = new Contact();
}
}

Then i m just creating a sample object of ticket class
Ticket tkt = new Ticket();

tkt.Seats.Add(new Seat { name = "Hello", is_primary = true, age = 20, seat_number = 12 });
tkt.Contact = new Contact { email = "a@b.com", emergency_name = "Dont know", mobile_number = "1234567" };

Then this is how you will create a xml using LINQ
XElement xe = new XElement("book_ticket",

new XElement("seat_details"),
new XElement("contact_detail"));

var _seats = xe.Element("seat_details");

foreach (var item in tkt.Seats)
{
XElement _seat_detail = new XElement("_seat_detail",
new XElement("seat_number", item.seat_number),
new XElement("name", item.name),
new XElement("age", item.age),
new XElement("is_primary", item.is_primary));

_seats.Add(_seat_detail);
}

var _contact = xe.Element("contact_detail");
_contact.Add(new XElement("email", tkt.Contact.email),
new XElement("mobile_number", tkt.Contact.mobile_number),
new XElement("emergency_name", tkt.Contact.emergency_name));

//now xe will hold your result xml


Suneel161, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Lakn2 on: 6/20/2011 [Member] Starter | Points: 25

Up
0
Down
try this

http://www.codeproject.com/KB/XML/XmlToClassAndBack.aspx

Thanks&Regards
LakshmiNarayana Nalluri.

Suneel161, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response