Skip to content

Instantly share code, notes, and snippets.

@whoo24
Created December 5, 2016 15:05
Show Gist options
  • Save whoo24/6f58bfae3299efc34b251dda36de4cd1 to your computer and use it in GitHub Desktop.
Save whoo24/6f58bfae3299efc34b251dda36de4cd1 to your computer and use it in GitHub Desktop.
객체의 관계까지 Xml로 Serialization 해주는 DataContractSerializer 샘플
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;
namespace DataContractSerializerSample {
[Serializable, KnownType(typeof(DerrivedSerializableModel))]
public class SerializableModel {
public SerializableModel node;
}
public class DerrivedSerializableModel : SerializableModel {
}
class Program {
static void Main (string[] args) {
string path = Path.Combine(Environment.CurrentDirectory, "sample.xml");
var settings = new XmlWriterSettings();
settings.Indent = true;
SerializableModel s1 = new SerializableModel();
SerializableModel s2 = new DerrivedSerializableModel();
s1.node = s2;
using (var writer = XmlWriter.Create(path, settings)) {
DataContractSerializer serializer = new DataContractSerializer(typeof(SerializableModel[]), null, 0x7FFF, false, true, null);
serializer.WriteObject(writer, new []{
s1, s2
});
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfSerializableModel xmlns:i="http://www.w3.org/2001/XMLSchema-instance" z:Id="1" z:Size="2" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" xmlns="http://schemas.datacontract.org/2004/07/ConsoleApplication1">
<SerializableModel z:Id="2">
<node z:Id="3" i:type="DerrivedSerializableModel">
<node i:nil="true" />
</node>
</SerializableModel>
<SerializableModel z:Ref="3" i:nil="true" />
</ArrayOfSerializableModel>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment