gpt4 book ai didi

c# - 将对象序列化为 XML

转载 作者:太空狗 更新时间:2023-10-29 22:33:30 26 4
gpt4 key购买 nike

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

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 接口(interface),因为私有(private)属性 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 对象

最佳答案

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

关于c# - 将对象序列化为 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11501294/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com