开发者

XmlDocument::Save() appends the xml in file

I want to keep a single XmlDocument object in a class and let methods make changes to it and save it.

using (FileStream fs = new FileStream(@"D:\Diary.xml", 
       FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
{
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(fs);

    // ... make some changes here

    xml开发者_如何学PythonDoc.Save(fs);
}

The above code makes two copies of the xml structure inside the file.


Try

fs.SetLength(0);

before Save call


Add:

fs.Position = 0;

before the Save call.


It seems a bit strange that fs.Position from Foole's solution didn't work.

An equivalent would be

fs.Seek(0, SeekOrigin.Begin);

Alternatively

instead of using the same filestream:

            //OrigPath is the path you're using for the FileReader

            System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(OrigPath);
            xmlDoc.Save(writer);
            writer.Close();


Alternatively even this would work...

        XmlDocument xmlDoc = new XmlDocument( );
        xmlDoc.Load( @"D:\Diary.xml" );

        //.... make some changes here
        XmlText node = xmlDoc.CreateTextNode( "test" );
        xmlDoc.DocumentElement.AppendChild( node );

        xmlDoc.Save( @"D:\Diary.xml" );
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜