Search code examples
c#xml-serialization

Serialize object to XML


For Binary serialization I use

public ClassConstructor(SerializationInfo info, StreamingContext ctxt) {

    this.cars = (OtherClass)info.GetValue("Object", typeof(OtherClass));
}
public void GetObjectData(SerializationInfo info, StreamingContext ctxt) {
    info.AddString(this.name);
    info.AddValue("Object", this.object);
}

I want to make the same thing for XML serialization (class implements IXmlSerializable interface, because of private property setters), but I don't know how to put an object to serializer (XmlWriter object).

public void WriteXml( XmlWriter writer ) {
    writer.WriteAttributeString( "Name", Name );
    writer. ... Write object, but how ???
}
public void ReadXml( XmlReader reader ) {
    this.Name = reader.GetAttribute( "Name" );
    this.object = reader. ... how to read ??
}

probably I can use something like this

XmlSerializer xsSubmit = new XmlSerializer(typeof(MyObject));
var subReq = new MyObject();
StringWriter sww = new StringWriter();
XmlWriter writer = XmlWriter.Create(sww);
xsSubmit.Serialize(writer, subReq);
var xml = sww.ToString(); // Your xml

but maybe there is simpler method that uses only XmlWriter object I get from WriteXml method argument


Solution

  • I've decided to go the way I wrote my question - to use XmlWriter object, which i have to use anyway, even if I go Ofer Zelig's way.

    namespace System.Xml.Serialization {
        public static class XmlSerializationExtensions {
            public static readonly XmlSerializerNamespaces EmptyXmlSerializerNamespace = new XmlSerializerNamespaces(
                new XmlQualifiedName[] {
                    new XmlQualifiedName("") } );
    
            public static void WriteElementObject( this XmlWriter writer, string localName, object o ) {
                writer.WriteStartElement( localName );
                XmlSerializer xs = new XmlSerializer( o.GetType() );
                xs.Serialize( writer, o, EmptyXmlSerializerNamespace );
                writer.WriteEndElement();
            }
    
            public static T ReadElementObject< T >( this XmlReader reader ) {
                XmlSerializer xs = new XmlSerializer( typeof( T ) );
                reader.ReadStartElement();
                T retval = (T)xs.Deserialize( reader );
                reader.ReadEndElement();
                return retval;
            }
        }
    }