2011-09-21 63 views
3

在過去的幾個小時裏,我一直在使用Windows Phone 7上的LINQ to XML掙扎。我只是想將新元素添加到現有的XML文件中。如何使用LINQ to XML將新元素添加到Windows Phone 7上的現有XML文件?

XElement newItem = new XElement("item",new XAttribute("id",3), 
           new XElement("content","Buy groceries"), 
           new XElement("status","false")); 

IsolatedStorageFile isFile = IsolatedStorageFile.GetUserStoreForApplication(); 
IsolatedStorageFileStream stream = new IsolatedStorageFileStream("/Items.xml", System.IO.FileMode.Open, isFile); 

XDocument loadedDoc = XDocument.Load(stream); 
loadedDoc.Add(newItem); 
loadedDoc.Save(stream); 

通常我遇到非常奇怪的行爲。有時我收到錯誤「IsolatedStorageFileStream不允許操作」。有時它是「根元素缺失」,有時候是「意外的XML聲明」,XML聲明必須是文檔中的第一個節點,並且不允許任何空格字符出現在它之前。例如,如果我將System.IO.FileMode.Open更改爲「創建」,我會得到「根元素缺失」,但除此之外,根據哪個錯誤發生,似乎沒有任何模式。

這一切似乎是導致該問題的我的XML文件:

<?xml version="1.0" encoding="utf-8" ?> 
<items> 
    <item id="1"> 
     <content>Get groceries</content> 
     <status>false</status> 
    </item> 
    <item id="2"> 
     <content>Wash your car</content> 
     <status>true</status> 
    </item> 
</items> 

它沒有什麼比這再簡單不過,我絕對相信我的聲明之前沒有任何空格實際的XML文件。 爲了讓這一切更奇怪,我下載了一個使用相同技術寫入XML文件的小示例應用程序。當我嘗試運行它,我得到一個非常熟悉的錯誤:

Unexpected XML declaration. The XML declaration must be the first node in the document, and no white space characters are allowed to appear before it.

這裏是鏈接到該線程:http://mobileworld.appamundi.com/blogs/petevickers/archive/2010/12/06/windows-phone-7-linq-to-xml-corruption.aspx/

昨天我安裝的Windows Phone SDK 7.1測試版。這可能會導致問題嗎?


這似乎是問題是在隔離存儲中定位xml文件。我已經創建了全新的項目和新的XML文件。

,這是我所擁有的惟一代碼:

// Constructor 
public MainPage() 
{ 
    InitializeComponent(); 
    var isFile = IsolatedStorageFile.GetUserStoreForApplication(); 
    var stream = isFile.OpenFile("file.xml", System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite); 
} 

我'仍然得到:不允許操作上IsolatedStorageFileStream。我試圖進入file.xml的屬性更改內置動作和複製到輸出目錄,但沒有奏效。我嘗試添加:

isFile.Dispose(); 

我也嘗試添加條件語句:

if (isFile.FileExists("file.xml"))... 

但他不能找到該文件。

我從來沒有如此卡住我的生活。請指教我還有什麼我可以嘗試。

回答

1

您正試圖保存到您加載的同一個流 - 但沒有「倒帶」到開始。我不知道隔離存放流是否可尋址的,但你可以嘗試只是改變了代碼:

XDocument loadedDoc = XDocument.Load(stream); 
loadedDoc.Add(newItem); 
stream.Position = 0; 
loadedDoc.Save(stream); 

另外,加載該文件,並關閉流,然後打開了一個新的在同一文件。請注意,您應該使用using語句在每次使用後關閉流,例如

using (var isFile = IsolatedStorageFile.GetUserStoreForApplication()) 
{ 
    using (var stream = isFile.OpenFile("/Items.xml", FileMode.Open)) 
    { 
     XDocument loadedDoc = XDocument.Load(stream); 
     stream.Position = 0; 
     loadedDoc.Add(newItem); 
     loadedDoc.Save(stream); 
    } 
} 
+0

不幸的是,我的代碼並沒有通過「XDocument loadedDoc = XDocument.Load(stream);」我會得到「根元素缺失」,所以我甚至無法嘗試。 – Booyaches

+0

我試着用**使用**語句來完成它,但是同樣,我得到XDocument的「Root元素缺失」loadedDoc = XDocument.Load(stream);.一般來說,加載我的XML文件到流中似乎有問題。 – Booyaches

+0

@Boyoyaches:這意味着你的文件是空的。 – SLaks