views:

58

answers:

1

Hi,

Can I use Linq-to-xml to persist my object state without having to use/know Xpath & XSD Syntax?

ie. really looking for simple but flexible way to persist a graph of object data (e.g. have say 2 or 3 classes with associations) - if Linq-to-xml were as simple as saying "persist this graph to XML", and then you could also query it via Linq, or load it into memory again/change/then re-save to the xml file.

+3  A: 

You don't usually need XPath or XSD to use LINQ-to-XML, but it also won't do what you want. XmlSerializer comes close , but is a tree serializer, not a graph serializer.

DataContractSerializer (.NET 3.0) does offer graph support via one of the overloaded constructors, but doesn't offer full control over the xml.

BinaryFormatter offers graph support and metadata-/type-based workings, but is very brittle if you ever change your assembly, and is not portable between platforms.

I suspect the thing to figure out is: is my data a tree or a graph? XmlSerializer may already do what you need.


using System;
using System.Runtime.Serialization;
using System.IO;
[DataContract]
public class Outer {
    [DataMember]
    public Inner Inner { get; set; }
}
[DataContract]
public class Inner {
    [DataMember]
    public Outer Outer { get; set; }
}
class Program {
    static void Main() {
        // make a cyclic graph
        Outer outer = new Outer(), clone;
        outer.Inner = new Inner { Outer = outer };

        var dcs = new DataContractSerializer(typeof(Outer), null,
            int.MaxValue, false, true, null);
        using (MemoryStream ms = new MemoryStream()) {
            dcs.WriteObject(ms, outer);
            ms.Position = 0;
            clone = (Outer)dcs.ReadObject(ms);
        }
        Console.WriteLine(ReferenceEquals(
            clone, clone.Inner.Outer)); // true
    }
}
Marc Gravell
It's actually a directed graph.
Greg
@Greg - then `DataContractSerializer` with `preserveObjectReferences` set to `true` might be the next thing to try. I *don't* recommend `BinaryFormatter`, except for a few specific scenarios.
Marc Gravell
Tks - I'll have a look into this
Greg