我想我可能已经找到了解决方案,但它涉及覆盖文件。它可能很脏,但它适用于我。
我在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中“保存”超载不可用。 –