2012-02-24 85 views
0

我試圖將用戶數據保存到Windows Phone(7.1)上的XML文件中。在這個過程中,我打開現有的XML文件,插入一個新節點,然後嘗試保存XML文件。雖然代碼在visual studio 2010中運行時沒有錯誤,但不會對文件進行更改。我懷疑問題是代碼將文件保存到其他位置。我嘗試使用XDocument的create命令創建一個XMLWriter,將文件的填充路徑作爲輸入參數,但Windows Phone系統中支持的System.XML.Linq(2.0.5)版本不支持此操作。如何在Windows Phone 7.1應用程序中編輯XML文件

的代碼如下:

  public void AddSwimGoal(SwimGoal SG)  
    { 
     string FileName = "Data/SwimGoals.xml"; 
     XDocument Doc = new XDocument(); 
     Doc = XDocument.Load(@FileName); 

     XElement Root = Doc.Root; 
     XElement NewSG = new XElement("SwimGoal"); 
     XAttribute Dist = new XAttribute("Distance", SG.Distance); 
     XAttribute MaxTD = new XAttribute("MaxTrainingDistance", SG.MaxTrainingDistance); 
     XAttribute ID = new XAttribute("ID", SG.ID); 
     XAttribute Name = new XAttribute("Name", SG.Name); 
     XAttribute StartDate = new XAttribute("StartDate", SG.StartDate); 
     XAttribute EndDate = new XAttribute("EndDate", SG.EndDate); 
     XAttribute DesiredTime = new XAttribute("DesiredTime", SG.Desiredtime); 
     XAttribute Stroke = new XAttribute("Stroke", SG.Stroke); 
     NewSG.Add(Dist, MaxTD, ID, Name, StartDate, EndDate, DesiredTime, Stroke); 
     Root.Add(NewSG); 
     XmlWriter Wr = Doc.CreateWriter(); 
     Doc.Save(Wr); 
    } 
+0

您是否嘗試重新載入已保存的xml文檔? – webdad3 2012-02-24 23:16:35

+0

是的,文件沒有改變。 – user640142 2012-02-25 00:39:06

回答

0

這是我用來保存我的XML到獨立存儲的代碼。你的想法可能是對的,就是將它保存在別的地方。以下可能會解決該問題。

   private void saveXML() 
       { 
        using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) 
        { 
         IsolatedStorageFileStream stream = store.OpenFile("myapp.Xml", FileMode.Create, FileAccess.Write); 
         _xdoc.Save(stream); 
         stream.Dispose(); 
        } 
       } 

嘗試改變了你添加元素到您的xml文件的方式:

      _xdoc = new XDocument(
            new XComment("Created " + DateTime.Now.ToLongTimeString()), 
            new XElement("a", 
            new XElement("b", 
            new XElement("c", this.tb_vehicleName.Text.ToString(), new XAttribute("id", 123)), 
            new XElement("d", "")))); 
+0

我試圖用「Data/SwimGoals.xml」代替「myapp.xml」而Doc.Save(流)代替_xdoc.Save(流),它收到一條錯誤消息,指出操作在IsolatedStorageFileStream上是不允許的。此錯誤發生在行IsolatedStorageFileStream stream = store.OpenFile(... – user640142 2012-02-25 04:55:16

+0

取出「數據/」只需使用SwimGoals.xml並看看有什麼作用。 – webdad3 2012-02-25 11:45:33

+0

消除數據/刪除錯誤消息,並允許我保存但是,當我在執行代碼後檢查保存的文件時,文件沒有變化,我在檢查文檔的結構之前使用Doc.ToString命令保存了文件,結果與原本一樣。謝謝@Jeff V – user640142 2012-02-25 15:59:37

0

我現在認識到,該文件未保存的原因是,當這個工作完成它做對模擬器,當時當文件被保存時,我會關閉模擬器。這破壞了文件,是我打開文件時找不到文件更改的原因。如果在重新打開模擬器時無法找到該文件,則打開文件的代碼將僅替換具有根節點的空白文檔。

相關問題