tags:

views:

269

answers:

3

If I want to work with XML, I usually design a class/bunch of classes that represent the data I need. Then I use XmlSerializer to read in the XML and write it out again.

This gives me strongly typed classes to work with whilst the XML is "in memory".

I can of course use Linq on these classes without any issue.

Should I be using Linq to XML, and if so - why?

To me, in my circumstances, it seems to server only to remove the strong typing!

A: 

I'd stick with the approach you have taken if I were you. There's very rarely a need to reimplement a well understood wheel, and you understand what you are trying to do with the serialization. More importantly, you know the issues surrounding them, so you can take care to implement workrounds - changing to L2XML would introduce a risk that is plain unnecessary.

Pete OHanlon
A: 

That depends what you want to do with it. It sounds like you just want to serialize and deserialize, in which case stick with your current approach. If you need to do more advanced things like create entirely different XML (using Projections) then LINQ to XML is very useful.

I often use LINQ to XML in places where previously I might have considered XSLT. In my experience developers understand LINQ to XML a lot more easily than understanding XSLT.

RichardOD
+1  A: 

As I see it, a big benefit of using the out-of-the-box XML serialization API is that you can get started with persisting your objects without having to do almost anything except a few rows of serialization/deserialization code.

However, there are drawbacks as well. For example, as far as I know XML serialization only works with public properties. If you would like to persist values of private properties you would have to write your own serialization logic. Also, if the exact schema and format of the resulting XML is important, it can be difficult to achieve using the built-in XML serialization.

Linq to XML gives great control over the produced XML as well as the ability to build objects from XML using query logic, but for plain serialization where you don't have special requirements on the output I should stick with the standard API.

Anders Fjeldstad
not to mention that the built in serialization doesn't handle versioning, afaict
Jeff Paquette
Regarding versioning: I think as long as you don't add mandatory fields to new versions of your objects and use the OptionalField attribute (of System.Runtime.Serialization) on your new properties you can utilize the built-in serialization.
Anders Fjeldstad
Regarding public properties - this would be fine if you use a data structure to model the XML and objects to encapsulate the behavior on the data structure. Data Structure = data; Object = data + behavior.
Aaron