Serializing an Object in 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 do the same for XML serialization (the class implements the IXmlSerializable interface, due to the settings of private property seters), but I do not know how to put the object in the 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 ?? } 

Maybe 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 a simpler method that uses only the XmlWriter object that I get from the WriteXml method argument

+5
source share
2 answers

I decided to go as I wrote my question - to use the XmlWriter object, which I should use anyway, even if I go to Ofer Zelig.

 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; } } } 
+3
source

Download the FairlyCertain A / B Test Library.

Inside the great code, you'll find the XML serializer class, inside SerializationHelper.cs .

Exposure:

  /// <summary> /// Given a serializable object, returns an XML string representing that object. /// </summary> /// <param name="obj"></param> /// <returns></returns> public static string Serialize(object obj) { XmlSerializer xs = new XmlSerializer(obj.GetType()); using (MemoryStream buffer = new MemoryStream()) { xs.Serialize(buffer, obj); return ASCIIEncoding.ASCII.GetString(buffer.ToArray()); } } 
+6
source

All Articles