標題說明了一切。我一直堅持這一天,並希望得到一些幫助。當主頁首次加載時,它會測試本地文件夾中的settings.xml並在未找到時複製它,我有一個主頁面和一個設置頁面。然後,當用戶打開設置頁面時,應該從本地文件夾加載詳細信息,以允許用戶在將它們從OnNavigatedFrom事件保存回本地文件夾之前進行編輯。如何在uwp應用程序中加載,編輯和保存xml
代碼從安裝文件夾加載到本地文件夾
// Has the file been copied already?
bool blFileExist = false;
try
{
await ApplicationData.Current.LocalFolder.GetFileAsync("settings.xml");
// No exception means it exists
blFileExist = true;
btnSettings.Foreground = new SolidColorBrush(Windows.UI.Colors.White);
}
catch (System.IO.FileNotFoundException)
{
// The file obviously doesn't exist
blFileExist = false;
btnSettings.Foreground = new SolidColorBrush(Windows.UI.Colors.Red);
}
catch (Exception)
{
}
if (!blFileExist)
{
try
{
// Cant await inside catch, but this works anyway
StorageFile stopfile = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync("settings.xml");
await stopfile.CopyAsync(ApplicationData.Current.LocalFolder);
}
catch (System.IO.FileNotFoundException)
{
}
catch (Exception)
{
}
}
代碼加載和保存設置頁面
private void loadSettings()
{
try
{
doc = XElement.Load("settings.xml");
nAIPlayers = int.Parse(doc.Element("ai_players").Value);
strCardBack = doc.Element("back").Value;
comboBoxAIPlayers.SelectedIndex = nAIPlayers - 1;
}
catch (System.IO.FileNotFoundException)
{
}
catch (Exception ex)
{
}
}
private async void saveSettings()
{
//try
//{
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("settings.xml");
using (Stream fileStream = await file.OpenStreamForWriteAsync())
{
doc.SetElementValue("ai_players", nAIPlayers);
doc.SetElementValue("back", "Back_0");
doc.Save(fileStream);
}
/*}
catch (System.IO.FileNotFoundException)
{
}
catch (Exception ex)
{
}*/
}
我認爲這個問題是我在訪問本地文件進行保存和加載它的安裝文件。結果是不管我保存它總是讀取原始settings.xml中的值
如何從本地文件夾加載此值?
doc = XElement.Load(「settings.xml」);
更新
在第一次迭代的代碼運行正常,並設置頁面代碼打開,因爲它應該。只有在離開設置頁面並運行saveSettings()方法後,它纔會失敗,並在重新加載設置頁面並運行loadSettings()時引發錯誤。
System.Xml.XmlException:根級別的數據無效。 5號線,12位
謝謝。我已經更新了很多。 – luigivampa
@luigivampa似乎你寫錯了XML文件,因此數據是錯誤的。最好 - 只是調試它,保存/將該文件複製到KnownFolder以查看它的外觀,或[使用ISE](http://stackoverflow.com/a/33063501/2681948) - 以某種方式打開文件並查看錯誤。 – Romasz