将对象序列化为XML

时间:2012-07-16 09:15:08

标签: c# xml-serialization

对于二进制序列化,我使用

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

我想为XML序列化做同样的事情(类实现IXmlSerializable接口,因为私有属性setter),但我不知道如何将对象放到序列化器(XmlWriter对象)。

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

我可能会使用像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

但也许有更简单的方法只使用我从WriteXml方法参数获得的XmlWriter对象

2 个答案:

答案 0 :(得分:5)

下载FairlyCertain A/B Testing library

在优秀的代码中,您将在SerializationHelper.cs内找到XML序列化程序类。

摘录:

    /// <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());
        MemoryStream buffer = new MemoryStream();
        xs.Serialize(buffer, obj);
        return ASCIIEncoding.ASCII.GetString(buffer.ToArray());
    }

答案 1 :(得分:3)

我决定采用我编写问题的方式 - 使用XmlWriter对象,无论如何我必须使用它,即使我采用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;
        }
    }
}