开发者

Xml.Serialization, Correct way to append

For my windows 7 phone application i serialize my object and save it to items.xml.

Now when i want to add more items to my items.xml i have a problem co's the writer.WriteEndElement(); has already been written. now what i can do is read all the items that are in items.xml save it in a list and then overwrite the current items.xml tough this puts heavy usage on the phone so i doubt its the correct way but is there any decent work around for this and thus decently append the file ? thanks !

using (var isfs = new IsolatedStorageFileStream(@"items.xml", FileMode.Append, store))
                    {
                        XmlWriterSettings settings = new XmlWr开发者_Python百科iterSettings();
                        settings.Indent = true;
                        using (var writer = XmlWriter.Create(isfs, settings))
                        {
                            writer.WriteStartElement("ToDoItem");
                            item.WriteXml(writer);
                            writer.WriteEndElement();
                            writer.Close();
                        }
                    }

Misc.

[XmlRoot("ToDoItem")]
    public class ToDoItem : IXmlSerializable{
    ...
}


Here is one way to write more than one object to an XMLSerializer:

List<Object> myobjects = new List<Object>( {myObject1, myObject2 } ); // IEnumerable Constructor

using (XMLSerializer xml = new XMLSerializer(typeof(List<Object>)))
{
     // write them to the file
     xml.Serialize(File.OpenWrite(filename), myobjects);
}

And to deserialize:

using (XMLSerializer xml = new XMLSerializer(typeof(List<object>)))
{
     List<Object> myobjects = xml.Deserialize(File.OpenRead(filename));
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜