C# 序列化一个对象,其中包含一个对象列表 [英] C# Serialize an object with a list of objects in it
问题描述
在 C# 中,如果我序列化一个包含对象列表的对象,它是否也会序列化该列表?
In C# if I serialize an object that has a list of objects in it will it also serialize the list?
示例
public class Move {
public string MoveName {get; set;}
public List<Tag> oTags = new List<Tag>;
}
public class Tag {
public string TagName {get; set;}
}
如果我序列化 move 中存储的所有标签是否也会被序列化?此外,如果它不会序列化列表,我将如何让它做到这一点?
If I serialize move will all the tags stored in move get serialized as well? Also if it will not serialize the list how would I go about making it do that?
<Move>
<MoveName>name</MoveName>
<Tag>Value</Tag>
...
</Move>
推荐答案
是的,使用 XmlSerializer
只要T,它就会序列化一个
List
(或在您的情况下为 Tag
)是可序列化的.
Yes, using the XmlSerializer
it will serialize a List<T>
so long as T
(or in your case Tag
) is serializable.
Move move = new Move { MoveName = "MyName" };
move.oTags.Add(new Tag { TagName = "Value1" } );
move.oTags.Add(new Tag { TagName = "Value2" } );
move.oTags.Add(new Tag { TagName = "Value3" } );
StringBuilder output = new StringBuilder();
var writer = new StringWriter(output);
XmlSerializer serializer = new XmlSerializer(typeof(Move));
serializer.Serialize(writer, move);
Console.WriteLine(output.ToString());
使用您当前的类结构输出:
This outputs using your current class structure as:
<?xml version="1.0" encoding="utf-16"?>
<Move xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<oTags>
<Tag>
<TagName>Value1</TagName>
</Tag>
<Tag>
<TagName>Value2</TagName>
</Tag>
<Tag>
<TagName>Value3</TagName>
</Tag>
</oTags>
<MoveName>MyName</MoveName>
</Move>
我会看看是否能找到一种方法来匹配您当前的 XML 架构,但您可以查找如何应用 XmlAttributes 并自行尝试.
I'll see if I can find a way to match your current XML schema, but you can look up how to apply XmlAttributes and play around with it yourself.
如果您将类声明更改为使用以下 XmlAttributes,您将获得与示例中相同的 XML 架构:
If you change your class declaration to use the following XmlAttributes, you will achieve the exact XML schema as in your example:
public class Move
{
[XmlElement(Order = 1)]
public string MoveName {get; set;}
[XmlElement(Order = 2, ElementName = "Tags")]
public List<Tag> oTags = new List<Tag>();
}
public class Tag
{
[XmlText]
public string TagName {get; set;}
}
序列化时会产生:
<?xml version="1.0" encoding="utf-16"?>
<Move xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MoveName>MyName</MoveName>
<Tags>Value1</Tags>
<Tags>Value2</Tags>
<Tags>Value3</Tags>
</Move>
这篇关于C# 序列化一个对象,其中包含一个对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!