With the help of XmlSerializer
we can convert the list of C# objects to XML document. Below is the example of converting your array list to XML.
First of all we need to add below two namespaces to the page.
using System.Xml.Serialization;
using System.IO;
The second step is to prepare your array list. In my example i am creating a class of Book with some attributes like Name of the book, Author of the Book etc.
[Serializable] public class Book { public string Name { get; set; } public string Author { get; set; } public string Publisher { get; set; } public int Pages { get; set; } public decimal Price { get; set; } }
The next step is to add some values to this class. Here i am creating a array of this class and adding 3 books to the array. The code is as below.
Book objBook = new Book(); objBook.Name = "Beginning JavaScript 4th Edition"; objBook.Author = "Paul Wilton"; objBook.Publisher = "Wrox"; objBook.Pages = 200; objBook.Price = (decimal)35.34; Book objBook_1 = new Book(); objBook_1.Name = "Head First C#"; objBook_1.Author = "Andrew Stellman"; objBook_1.Publisher = "o reilly"; objBook_1.Pages = 365; objBook_1.Price = (decimal)23.46; Book objBook_2 = new Book(); objBook_2.Name = "RESTful Web Services"; objBook_2.Author = "Leonard Richardson"; objBook_2.Publisher = "o reilly"; objBook_2.Pages = 200; objBook_2.Price = (decimal)235.34; Book[] bookArry = new Book[3]; bookArry[0] = objBook; bookArry[1] = objBook_1; bookArry[2] = objBook_2;
Now I have a array of class book which i want to convert to XML. Just use below sample code to convert your array to XML.
XmlSerializer Book_Serializer = new XmlSerializer(bookArry.GetType()); StringWriter Writer = new StringWriter(); Book_Serializer.Serialize(Writer, bookArry); string strXML = Writer.ToString();
And finally the output of above example is as below.
<?xml version="1.0" encoding="utf-16"?> <ArrayOfBook xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Book> <Name>Beginning JavaScript 4th Edition</Name> <Author>Paul Wilton</Author> <Publisher>Wrox</Publisher> <Pages>200</Pages> <Price>35.34</Price> </Book> <Book> <Name>Head First C#</Name> <Author>Andrew Stellman</Author> <Publisher>o reilly</Publisher> <Pages>365</Pages> <Price>23.46</Price> </Book> <Book> <Name>RESTful Web Services</Name> <Author>Leonard Richardson</Author> <Publisher>o reilly</Publisher> <Pages>200</Pages> <Price>235.34</Price> </Book> </ArrayOfBook>
This is the example of array to xml asp.net, folks give me your feedback to improve quality of blog.