5

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

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 接口,因为私有属性设置器),但我不知道如何将对象放入序列化程序(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 ??
}

也许我可以使用这样的东西

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 对象

4

2 回答 2

6

下载FairlyCertain A/B 测试库

在出色的代码中,您会发现一个 XML 序列化程序类,在SerializationHelper.cs.

摘录:

    /// <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());
        }
    }
于 2012-07-16T09:18:15.730 回答
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;
        }
    }
}
于 2012-07-18T12:55:18.350 回答