我想我可能已經找到了解決方案,但它涉及覆蓋文件。它可能很髒,但它適用於我。
我在ApplicationData.Current.LocalFolder.Path
位置創建了一個xml文件。在安裝目錄(Package.Current.InstalledLocation.Path)
中工作可能很困難,因爲其中的所有文件都是砂箱式的,您將無權修改它們。
所以第一部分會看起來像這樣。
string customerXMLPath =
Path.Combine(ApplicationData.Current.LocalFolder.Path, "XML/Customers.xml");
之後,您可以運行您的XDocument
代碼。但是請不要打電話xmlDoc.Save(customerXMLPath)
,因爲這不適用於UWP應用程序。
所以第二部分看起來像這樣。就像你已經。
XDocument xmlDoc = XDocument.Load(customerXMLPath);
var updateQuery = from r in xmlDoc.Descendants("Customer")
where r.Element("CustomerId").Value == txtCustomerId.Text
select r;
foreach (var query in updateQuery)
{
query.Element("State").SetValue(txtState.Text);
}
最後一部分是你必須保存的內容你XDocument
的文件,文件中已經覆蓋的任何內容。由於這是一個await
操作,因此建議您也使用方法async
。應該使用StorageFolder
和StorageFile
來獲取位置和文件重新創建。
所以最後一部分看起來像這樣。
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
var newfile = await storageFolder.CreateFileAsync("Customers.xml",
CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(newfile, xmlDoc.ToString());
所以完整的例子看起來像這樣。
using System.Xml.Linq;
using Windows.Storage;
using System.IO;
using System.Linq;
private void cmdStart_Click(object sender, RoutedEventArgs e)
{
SaveXml();
}
private async void SaveXml()
{
string XML_DATA_FILE = "Customer.xml";
string customerXMLPath = Path.Combine(ApplicationData.Current.LocalFolder.Path, XML_DATA_FILE);
if (File.Exists(xmlPath))
{
XDocument xmlDoc = XDocument.Load(customerXMLPath);
var updateQuery = from r in xmlDoc.Descendants("Customer")
where r.Element("CustomerId").Value == txtCustomerId.Text
select r;
foreach (var query in updateQuery)
{
query.Element("State").SetValue(txtState.Text);
}
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
var newfile = await storageFolder.CreateFileAsync(XML_DATA_FILE,
CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(newfile, xmlDoc.ToString());
}
}
我希望這有助於並提供一些指導。
乾杯。
[保存和XDocument到「使用流」中的文件可能的重複](http://stackoverflow.com/questions/35090648/save-and-xdocument-to-a-file-in-a-using -stream) – BrunoLM
這個問題並不完全相同,但我認爲這裏的答案也適用於此 – BrunoLM
根據文檔,在UWP中「保存」超載不可用。 –