Windows 8 store app XmlWriter does not write anything to file

I am not very well versed with .NET's XML libraries and trying to wrap my head around IXmlSerializable interface. I am developing a windows store app (W8) and wish to use the IXmlSerializable interface, however am running into issues. XmlTextWriter is not available in windows store apps so I am using XmlWriter's factory method but my code does not output anything to the XML file (its blank).

If I use XmlSerializer, the XML file is output as expected, but wish to implement IXmlSerializable since in my production app I will have private fields.

Here is the sample code I am using

public class XMLTest : IXmlSerializable
{
    private string name;
    public string Name { get { return this.name; } set { this.name = value; } }

    private XMLTest() { }

    public XMLTest(string name)
    {
        this.name = name;
    }

    public System.Xml.Schema.XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(System.Xml.XmlReader reader)
    {
        throw new NotImplementedException();
    }

    public void WriteXml(System.Xml.XmlWriter writer)
    {
        writer.WriteAttributeString("Name", this.name);
    }
}

In my XAML code behind

private async void saveButton_Click(object sender, RoutedEventArgs e)
    {
        XMLTest t = new XMLTest("test name");

        StorageFolder folder = ApplicationData.Current.LocalFolder;
        Stream fs = await folder.OpenStreamForWriteAsync("testingXML.xml", CreationCollisionOption.ReplaceExisting);
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.ConformanceLevel = ConformanceLevel.Auto;
        var x = XmlWriter.Create(fs, settings);

        //XmlSerializer xs = new XmlSerializer(t.GetType());
        //xs.Serialize(fs, t);

        t.WriteXml(x);
        fs.Dispose();
    }
Jon Skeet
people
quotationmark

Given the comment thread - this was about not closing all the resources. You're disposing fs (manually, if no exceptions are thrown) but not x. You should really use using statements for everything like this:

using (var stream = await folder.OpenStreamForWriteAsync(...))
{
    var settings = new XmlWriterSettings { ConformanceLevel = ConformanceLevel.Auto };
    using (var writer = XmlWriter.Create(stream, settings))
    {
        t.WriteXml(writer);
    }
}

people

See more on this question at Stackoverflow