devnet247 (3) [Avatar] Offline
#1
HI,
I find this book quite good compared to others.
I was looking at the example where you create a "Book Object" from the books.xml file.

I was wondering if you could post an example to do the opposite such us
convert a book Object to an xml?

Thanks a lot
steve.eichert (22) [Avatar] Offline
#2
Re: Create an Xml Element From a Book Object?
Gabriel,

In chapter 11 we cover how to create XML from objects retrieved via LINQ to SQL. While the code sample is showing how to create the XML with LINQ to SQL objects, it would work the same for in memory objects. I've included a simplified example below. If you're interested in a more complete example I'd encourage you to download the sample code located here:

http://linqinaction.net/files/folders/linqinaction/entry1952.aspx

Below is a example that is using a simplified Book object. If you're interested in more specific examples let me know.

var book = new Book {
Title = "LINQ in Action",
Publisher = "Manning",
PublicationDate = "January, 2008",
};

var xml = new XElement("Book",
new XElement("Title", book.Title),
new XElement("Publisher", book.Publisher),
new XElement("PublicationDate", book.PublicationDate)
);

Cheers,
Steve
devnet247 (3) [Avatar] Offline
#3
Re: Create an Xml Element From a Book Object?
Thanks a lot for your reply.
In chapter 11 you have createObject from xml but not the other way round.
EG
var books =
from bookElement in booksXml.Elements("book")
select new LinqInAction.LinqBooks.Common.Book {
Title=(string)bookElement.Element("title"),
Publisher=new Publisher {
Name=(string)bookElement.Element("publisher")
},
PublicationDate=(DateTime)bookElement.Element("publicationDate"),
Price=(decimal) bookElement.Element("price"),
Isbn = (string) bookElement.Element("isbn"),
Notes=(string) bookElement.Element("notes"),
Summary=(string) bookElement.Element("summary"),
Authors=
from authorElement in bookElement.Descendants("author")
select new Author {
FirstName=(string) authorElement.Element("firstName"),
LastName=(string) authorElement.Element("lastName")
},
Reviews=
from reviewElement in bookElement.Descendants("review")
select new Review {
User=new User {
Name =(string) reviewElement.Element("user")
},
Rating=(int) reviewElement.Element("rating"),
Comments=(string) reviewElement.Element("comments")
}
};



but I was trying to do the other way round with little success.I will give another go

thanks again
fabrice.marguerie (224) [Avatar] Offline
#4
Re: Create an Xml Element From a Book Object?
As Steve wrote, there is an example that shows how to create XML from LINQ to SQL entities. See listing 11.11. It works the same for any kind of objects.
devnet247 (3) [Avatar] Offline
#5
Re: Create an Xml Element From a Book Object?
Thanks a lot for your prompt reply.

all sorted now.