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
}
}