Problems with XML, LINQ, and XDocument.Save

I am having problems saving xml files after making changes to them. Today I spent the whole day trying to figure it out, and I didn't go anywhere.

I have this xml document:

<?xml version=1.0" encoding="utf-8"?>
<content>
      <weapon id="1234" name="blahblah">
         <note info="blah blah" />
      </weapon>
      <weapon id="5678" name="blahblah2">
         <note info="blah blah" />
      </weapon>
</content>

This is what I came up with so far not working (Edited to show how I read the file):

FileOpenPicker openPicker = new FileOpenPicker();
openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
openPicker.FileTypeFilter.Add(".xml");

StorageFile gfile = await openPicker.PickSingleFileAsync()

fileContent = await FileIO.ReadTextAsync(gfile, Windows.Storage.Streams.UnicodeEncoding.Utf8);

Xdocument  xml = XDocument.Parse(fileContent);

xml.Descendants("weapon").Where(c => c.Attribute("id").Value.Equals("5678")).FirstorDefault().Remove();

IRandomAccessStream writeStream = await gfile.OpenAsync(FileAccessMode.ReadWrite);
Stream stream = writeStream.AsStreamForWrite();

xml.Save(stream);

The resulting XML document will be something like this:

<?xml version=1.0" encoding="utf-8"?>
<content>
      <weapon id="1234" name="blahblah">
         <note info="blah blah" />
</content>apon>
      <weapon id="5678" name="blahblah2">
         <note info="blah blah" />
      </weapon>
</content>

If I try to use FileAccessMode.ReadWriteNoCopyOnWrite for OpenAsync, the file ends with 0 bytes.

Does anyone know how I can write this file correctly while still using XDocument.Save?

+3
source share
5 answers

It turns out that this problem is more complicated than it might seem at first glance.

Problems we need to solve include

  • write to file asynchronously
  • , IO
  • ,

, , - XML System.IO.MemoryStream, . , . , ( IO, Windows, ), , . , , . :

MemoryStream ms = new MemoryStream()

xml.Save(ms, SaveOptions.DisableFormatting);

await ms.CopyToAsync(gfile);

CopyToAsync:

using System.IO;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Storage;
using Windows.Storage.Streams;

internal static class Extensions
{
    public static async Task CopyToAsync(this MemoryStream source, StorageFile file)
    {
        using (IRandomAccessStream raStream = await file.OpenAsync(FileAccessMode.ReadWrite))
        {
            using (IOutputStream stream = raStream.GetOutputStreamAt(0))
            {
                await stream.WriteAsync(source.GetWindowsRuntimeBuffer());
                await stream.FlushAsync();
            }

            raStream.Size = raStream.Position;
        }
    }
}
+1

System.IO.File.WriteAllText?

XDocument xml = XDocument.Load(xmlFilePath);

System.IO.File.WriteAllText(xmlFilePath, string.Format(@"<?xml version=""1.0""?>{0}{1}", Environment.NewLine, xml));
+2

, . ...

var local = Windows.Storage.ApplicationData.Current.LocalFolder;
var file = await local.GetFileAsync("test.xml");
var data = await FileIO.ReadTextAsync(file);
var xml = XDocument.Parse(data);

xml.Descendants("weapon").Where(c => c.Attribute("id").Value.Equals("5678")).FirstOrDefault().Remove();

file = await local.CreateFileAsync("test.xml", CreationCollisionOption.ReplaceExisting);
var writeStream = await file.OpenStreamForWriteAsync() as Stream;

xml.Save(writeStream);

writeStream.Flush();

test.xml - XML.

0

, XML , , XDocument.Save , .

WinRT , .

/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{

    public List<DataStructure> DataList { get; set; }

    public MainPage()
    {
        this.InitializeComponent();
        DataList = Enumerable.Range(0, 25).Select(i => new DataStructure() { Id = i, Data = string.Format("Number : {0}", i) }).ToList();
        this.Loaded += MainPage_Loaded;
    }

    async void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        this.Loaded -= MainPage_Loaded;
        //var xmlDocument =
        //    new XDocument(
        //        new XElement("DataList",
        //            DataList.Select(dataItem =>
        //                new XElement("DataItem",
        //                    new XAttribute("id", dataItem.Id), new XAttribute("data", dataItem.Data)))));

        var rootNode = new XElement("DataList");
        var xmlDocument = new XDocument(rootNode);
        foreach (var dataItem in DataList)
        {
            rootNode.Add(new XElement("DataItem",
                            new XAttribute("id", dataItem.Id), new XAttribute("data", dataItem.Data)));
        }

        FileSavePicker savePicker = new FileSavePicker();
        savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
        // Dropdown of file types the user can save the file as
        savePicker.FileTypeChoices.Add("XML Document", new List<string>() { ".xml" });
        // Default file name if the user does not type one in or select a file to replace
        savePicker.SuggestedFileName = "New Xml Document";

        StorageFile file = await savePicker.PickSaveFileAsync();
        // Process picked file
        if (file != null)
        {
            // Store file for future access
            var fileToken = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(file);
            var writterStream = await file.OpenStreamForWriteAsync();
            xmlDocument.Save(writterStream);
        }

    }

WinRT VS2012 (RC). MainPage.cs, . DataStructures, XDocument . , , XDocument. ( ). , write, .

0

FileStream, .

public static async Task SaveXMLAsync(XDocument linqXml, StorageFolder localFolder, string filename)
{
  // Create a storage file
  StorageFile file = await localFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

  // Write the XML to a File Stream.
  using (FileStream sourceStream = new FileStream(file.Path, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true))
  {
    linqXml.Save(sourceStream);

    // Async flush to disk.
    await sourceStream.FlushAsync();
  };
}
0

All Articles