Separate object fields into two files by serializing DataContract


I an using DataContractSerializer and i want to separate data of same object into multiple files.

public class TestObj
    protected double field1 = 0.0;

    protected double field2 = 0.0;

Specifically I want to save field1 in one XML file and field2 in a different XML file. Is there any way to do that using data contract serialization?

This is how I am serializing currently:

DataContractSerializer serializaer = new DataContractSerializer(GetType(), null,
              0x7FFFFFFF /*maxItemsInObjectGraph*/,
              false /*ignoreExtensionDataObject*/,
              true /*preserveObjectReferences : this is most important to me */,
              null /*dataContractSurrogate*/);
var fs = File.Open(fName, FileMode.Create);
serializaer.WriteObject(fs, this);

return true;
asked on Stack Overflow Oct 13, 2019 by Ameer Mansour • edited Oct 14, 2019 by dbc

2 Answers


I can suggest using Custom Xml Writer paired with serializer.

public class CustomWriter : XmlTextWriter
    public CustomWriter(TextWriter writer) : base(writer) { }
    public CustomWriter(Stream stream, Encoding encoding) : base(stream, encoding) { }
    public CustomWriter(string filename, Encoding encoding) : base(filename, encoding) { }

    public List<string> FieldList { get; set; }

    private string _localName;

    public override void WriteStartElement(string prefix, string localName, string ns)
        if (!FieldList.Contains(localName))
            base.WriteStartElement(prefix, localName, ns);
            _localName = localName;

    public override void WriteString(string text)
        if (!FieldList.Contains(_localName))

    public override void WriteEndElement()
        if (!FieldList.Contains(_localName))
            _localName = null;

Use it as follows:

var data = new TestObj();

var serializer = new DataContractSerializer(
    typeof(TestObj), null, 0x7FFFFFFF, false, true, null);

using (var writer = new CustomWriter(Console.Out)) // Specify filename or stream instead
    writer.Formatting = Formatting.Indented;
    writer.FieldList = new List<string> { "field1", "field3" }; // Specify fields to ignore
    serializer.WriteObject(writer, data);

Just specify a list of fields that should be ignored in the FieldList property.

Of course, with this way, the DataContractSerializer will intermediate create xml with all the elements contained in the class. And only after that our custom writer will filter them. But it will happen on the fly, very quickly and effectively.

answered on Stack Overflow Oct 13, 2019 by Alexander Petrov

Once you serialise the whole object you can then split it using Linq to XML.

Oh, I even found an example how to do it at How to Split an XML file into multiple XML Files.

answered on Stack Overflow Oct 13, 2019 by tymtam

User contributions licensed under CC BY-SA 3.0