0

我正在尝试将一些数据从对象写入 XML 文档,并且正在关注在线教程,但是我遇到了一个我似乎无法理解的问题,我用来启动创建的代码文档是using (XmlWriter writer = XmlWriter.Create("myData.xml")),我收到“myData.xml”错误,我得到的错误是:

The best overload method match for 'System.Xml.XmlWriter.Create(System.Xml.XmlWriter)'
has some invalid arguments

Argument 1: cannot convert from 'string' to 'System.Xml.XmlWriter'

XmlWriter 与 Windows Phone 兼容吗?如果不是,我是否必须更改写入文件的大量代码?

编辑:这是我的代码

        string output = SerializeToString<AppData>(rulesData);

        using (XmlWriter writer = XmlWriter.Create(output))
        {
            writer.WriteStartDocument();
            writer.WriteStartElement("myData");

            writer.WriteElementString("Starting Cash", rulesData.myStartingCash);
            writer.WriteElementString("Land on Go Data", rulesData.myLandOnGo);
            writer.WriteElementString("Free Parking Data", rulesData.myFreeParking);
            writer.WriteElementString("Full Circuit Data", rulesData.myFullCircuit);
            writer.WriteElementString("Auction Data", rulesData.myAuction);
            writer.Flush();

            writer.WriteEndElement();
            writer.WriteEndDocument();
        }

谢谢!-瑞安

4

1 回答 1

1

您可以使用以下代码:

   public static void SerializeToStream<T>(Stream stream, object model)
   {
        var writer = XmlWriter.Create(stream);
        var s = new XmlSerializer(typeof(T));
        s.Serialize(writer, model);
    }

    public static string SerializeToString<T>(object model)
    {
        var xmlSer = new XmlSerializer(typeof(T));

        using (var stream = new MemoryStream())
        {
            SerializeToStream<T>(stream, model);
            var s = stream.ToArray();
            return System.Text.Encoding.UTF8.GetString(s, 0, s.Length);
        }
    }

    public static void SerializeToFile<T>(string filename, object model)
    {
        using (FileStream stream = File.Open(filename, FileMode.Create))
        {
            SerializeToStream<T>(stream, model);
        }
    }

您的代码无法编译,因为您将字符串而不是流传递给 XmlWriter

用法:

  string output = SerializeToString<ClassName>(instanceOfClass);
于 2012-12-08T20:10:33.340 回答