views:

29

answers:

1

I am using LINQ-To-SQL for database.

I am returning the xml content from my web service as follow:
The code:

DataClassesDataContext dc = new DataClassesDataContext();
[WebMethod]
    public List<Books> getBooks()
    {
        return dc.Books.ToList();    
    }

Output:

<ArrayOfBook>
−
<Book>
<bookID>1</bookID>
<title>Programming with Java</title>
<author>Balagurusami</author>
<summary>Summary1</summary>
</Book>
−
<Book>
<bookID>2</bookID>
<title>Programming with C</title>
<author>M.M.Patel</author>
<summary>Summary2</summary>
</Book>
−
<Book>
<bookID>3</bookID>
<title>ASP in 21 Days</title>
<author>K.J. Malai</author>
<summary>Summary3</summary>
</Book>
−
<Book>
<bookID>4</bookID>
<title>Book Title</title>
<author>autho1</author>
<summary>summary4</summary>
</Book>
</ArrayOfBook>

Question:

How can I put custom attributes & nodes in my output?

+1  A: 

Is the XML for human consumption? This is one of those areas where developers get stuck in a rut--they have this perception of what the XML "should" look like, and spend countless hours messing around with attributes and IXmlSerializable in order to get it to look the way they want. After all that wasted time they then sadly realize their application runs no differently than it did when they let the damn framework serialize their classes the way XmlSerializer wanted to.

Advice: Don't do it. Walk away. Work on something you actually need to work on.

Wait, you're still reading this? Oh well, guess you have to learn somehow.

Two options: Implement IXmlSerializable or use attributes on your properties. I would strongly suggest you go with option two. With the interface, you must construct and parse the xml yourself, which is harder than it sounds. This is even with the advent of the linq to xml classes (XElement etal). I've done that before and it ate up a week of my time dealing with this or that little niggling issue.

Attributes such as XmlAttribute or XmlElement are the quickest route to instruct the xml serializer how to generate your class' XML. There are some situations (like collection properties) where you will find it hard to massage the xml using attributes the way you want it (smirk).

So attributes are the definite better option. Unfortunately for you, you're serializing linq to sql entities--generated code. You can edit the generated code to add the attributes, but now you're screwed whenever you have to regenerate. Are you starting to get the feeling you shouldn't worry so much about what your xml looks like?

So, in your case, you have no option but to add partial classes for each of your entities and implement IXmlSerializable You can construct your xml many different ways (using 2.0 classes, linq to xml classes, or by using freaking StringBuilder). I'd suggest concentrating on the linq to xml classes. If you really want to abuse yourself this way.

Will