簡體   English   中英

XmlDocument::Save() 將 xml 附加到文件中

[英]XmlDocument::Save() appends the xml in file

我想在一個類中保留一個 XmlDocument 對象,並讓方法對其進行更改並保存它。

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

    xmlDoc.Save(fs);
}

上面的代碼在文件中制作了兩個 xml 結構的副本。

嘗試

fs.SetLength(0);

在保存通話之前

添加:

fs.Position = 0;

在 Save 調用之前。

來自 Foole 解決方案的 fs.Position 不起作用似乎有點奇怪。

一個等價物是

fs.Seek(0, SeekOrigin.Begin);

或者

而不是使用相同的文件流:

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

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

或者,即使這樣也可以工作......

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM