Windows 8 store app XmlWriter does not write anything to file

感情迁移 提交于 2019-12-25 03:56:06

问题


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();
    }

回答1:


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);
    }
}


来源:https://stackoverflow.com/questions/24615574/windows-8-store-app-xmlwriter-does-not-write-anything-to-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!