1

我有如下收藏类

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 与 Testcoll 一样具有标签“ArrayOfInt”。但我想将此名称更改为不同的“MyCollection”。

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

4

2 回答 2

1

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

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

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

XmlSerializer serializer = new XmlSerializer(typeof(Collection<int>), new XmlRootAttribute("MyCollection"));
serializer.Serialize(writer, Testcoll);
于 2012-06-21T14:33:07.830 回答
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();
}
于 2014-04-14T14:15:39.250 回答