是的,只要(或在您的情况下)是可序列化的,使用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>