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

发布于 2024-08-22 12:04:34 字数 350 浏览 3 评论 0原文

我想在类中保留单个 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 结构的两个副本。

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

    xmlDoc.Save(fs);
}

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

浊酒尽余欢 2024-08-29 12:04:34

尝试

fs.SetLength(0);

保存通话前

Try

fs.SetLength(0);

before Save call

懒的傷心 2024-08-29 12:04:34

添加:

fs.Position = 0;

在 Save 调用之前。

Add:

fs.Position = 0;

before the Save call.

淡忘如思 2024-08-29 12:04:34

愚人解决方案中的 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();

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();
夜唯美灬不弃 2024-08-29 12:04:34

或者,即使这样也行得通......

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

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" );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文