繁体   English   中英

如何xml序列化包含c#中其他类对象的对象?

[英]How to xml serialize object containing objects of other class in c#?

我想 xml 序列化一个包含其他自定义对象的自定义对象。 我像下面那样做,但它不起作用。

class A()
{
public B b;
}

class B()
{
public int a;
}

System.Xml.Serialization.XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(typeof(A));  
XmlAttributes xmlAttributes = new XmlAttributes();   
System.IO.StreamWriter file = new System.IO.StreamWriter(   @"d:\SerializationOverview.xml");
writer.Serialize(file, new A());  
file.Close();

结果是:

<A>
</A>

首先, AB需要标记为public

new A()b要序列化的值; 它不会序列化空值。 给它一个值:

writer.Serialize(file, new A { b = new B { a = 123 } });

另外:尝试优先选择属性而不是公共字段。

例如:

using System.IO;
using System.Xml.Serialization;
public class A
{
    public B B { get; set; }
}
public class B
{
    public int A {get;set;}
}
static class Program
{
    static void Main()
    {
        var writer = new XmlSerializer(typeof(A));
        using (var file = File.Create(@"SerializationOverview.xml"))
        {
            writer.Serialize(file, new A { B = new B { A = 123 } });
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM