IXmlSerializable更改xml标记名称

时间:2012-06-21 14:28:05

标签: c# ixmlserializable

我的课程集合如下

public class MyClass:IXmlSerializable
{
    int vesrion;
    private Collection<int> testcoll;
}

序列化它我写了WriteXML如下

public void WriteXml(XmlWriter writer)
{

    writer.WriteAttributeString("Version", this.vesrion.ToString());    

    XmlSerializer serializer = new XmlSerializer(typeof(Collection<int>));
    serializer.Serialize(writer, Testcoll);
 }

现在输出xml的标签为“ArrayOfInt”,与Testcoll相同。但我想将此名称更改为不同的“MyCollection”。

请告诉我如何实现这一目标。

2 个答案:

答案 0 :(得分:1)

在字段上使用属性,如下所示:

[XmlElement(ElementName = "MyCollection")]
private Collection<int> testcoll;

编辑:@comments,错过了这些细节,请参阅下面的答案(编译和测试)

XmlSerializer serializer = new XmlSerializer(typeof(Collection<int>), new XmlRootAttribute("MyCollection"));
serializer.Serialize(writer, Testcoll);

答案 1 :(得分:0)

另一种不创建新XmlSerializer的方法:

public void WriteXml(XmlWriter writer)
{
    writer.WriteAttributeString("Version", vesrion.ToString(CultureInfo.InvariantCulture));
    writer.WriteStartElement("MyCollection");
    foreach (int collint in Testcoll)
    {
        writer.WriteElementString("int", collint.ToString(CultureInfo.InvariantCulture));
    }
    writer.WriteEndElement();
}