在C#中如果我序列化一个包含对象列表的对象,它还会序列化列表吗?
实施例
public class Move {
public string MoveName {get; set;}
public List<Tag> oTags = new List<Tag>;
}
public class Tag {
public string TagName {get; set;}
}
如果我序列化移动,那么存储在move中的所有标签也会被序列化吗?此外,如果它不会序列化列表,我将如何做到这一点?
<Move>
<MoveName>name</MoveName>
<Tag>Value</Tag>
...
</Move>
答案 0 :(得分:9)
是的,使用XmlSerializer
只要List<T>
(或在您的情况下T
)可序列化,它就会序列化Tag
。
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());
使用您当前的类结构输出:
<?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并自行使用它。
编辑:
如果更改类声明以使用以下XmlAttributes,您将获得与示例中相同的XML模式:
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>
答案 1 :(得分:3)
您确定您的课程声明在您的问题中是否正确?
您只是声明Public Move
,应该是Public class Move
试试此代码
XmlSerializer serializer = new XmlSerializer(typeof(YourClass));
在你的情况下
Move m = new Move();
m.oTags.Add(new Tag() { TagName = "X" });
m.oTags.Add(new Tag() { TagName = "XX" });
XmlSerializer x = new XmlSerializer(typeof(Move));
System.IO.Stream s;
var xmlwriter = System.Xml.XmlWriter.Create("C:\\MXL.txt");
x.Serialize(xmlwriter, m);
<强>输出强>
<?xml version="1.0" encoding="utf-8"?>
<Move xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<oTags>
<Tag>
<TagName>X</TagName>
</Tag>
<Tag>
<TagName>XX</TagName>
</Tag>
</oTags></Move>
答案 2 :(得分:1)