2012-12-08 123 views
0

我試圖從一個對象寫入一些數據到一個XML文檔,然後在線教程,但是我遇到了一個我似乎無法理解的問題,我使用的啓動文件的創建using (XmlWriter writer = XmlWriter.Create("myData.xml")),我得到一個錯誤的「myData.xml」的代碼,我得到的錯誤是:在Windows Phone 7中寫入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' 

是隨着Windows Phone的XmlWriter兼容?如果不是,我將不得不改變寫入文件的大量代碼嗎?

編輯:這是我的代碼

 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(); 
     } 

謝謝! -Ryan

回答

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); 
+0

對於一些原因我無法訪問序列化SerializeToStream 和XmlSerializer,我已經包含了System.Xml.Serialization,有什麼想法嗎?請記住,這是在Windows Phone 7平臺上,從我以前的經驗來看,它缺少一些可用於桌面應用程序的功能 – TotalJargon

+0

@TotalJargon抱歉忘了添加它 – thumbmunkeys

+0

righto,爲什麼我不能使用XmlSerilizer? – TotalJargon