从XML文档中删除元素并保存旧文件 [英] Deleting an element from XML document and saving over old file

查看:85
本文介绍了从XML文档中删除元素并保存旧文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

*好的,所以我删除了程序,foreach (var elem in doc.Document.Descendants("Profiles"))行需要使用"Profile".但是现在在我的XML文档中,每个删除的元素都有一个空的Profile元素,因此,如果xml示例(位于问题底部)中的所有项目都被删除,我将得到以下内容: *

* ok, so I got the program to delete, the line foreach (var elem in doc.Document.Descendants("Profiles")) needed "Profile" instead. BUT now in my XML doc there is an empty Profile Element for each one deleted, so If all the items in the xml example(at bottom of question) get deleted I'm left with this:*

<?xml version="1.0" encoding="utf-8"?>
<Profiles>
  <Profile />
  <Profile />
</Profiles>

=========================下面的原始问题=================== =============

=========================ORIGINAL QUESTION BELOW=================================

我正在使用以下代码从XML文件中删除元素及其子元素,但保存时并未将其从文件中删除.有人可以让我知道为什么这是不正确的吗?

I'm using the following code to remove a element and it's children from an XML file, BUT it isn't removing them from the file upon saving. Could someone let me know why this is incorrect?

    public void DeleteProfile()
    {
        var doc = XDocument.Load(ProfileFile);
        foreach (var elem in doc.Document.Descendants("Profiles"))
        {
            foreach (var attr in elem.Attributes("Name"))
            {
                if (attr.Value.Equals(this.Name))
                    elem.RemoveAll();
            }
        }
        doc.Save(ProfileFile,
        MessageBox.Show("Deleted Successfully");
    }

以下XML格式的示例

<?xml version="1.0" encoding="utf-8"?>
<Profiles>
  <Profile Name="MyTool">
    <ToolName>PC00121</ToolName>
    <SaveLocation>C:\Users\13\Desktop\TestFolder1</SaveLocation>
    <Collections>True.True.True</Collections>
  </Profile>
  <Profile Name="TestProfile">
    <ToolName>PC10222</ToolName>
    <SaveLocation>C:\Users\14\Desktop\TestFolder2</SaveLocation>
    <Collections>True.False.False</Collections>
  </Profile>
</Profiles>

推荐答案

我假设您要删除具有其名称的配置文件:

I assume you want to remove a profile given its name:

private static void RemoveProfile(string profileFile, string profileName)
{
    XDocument xDocument = XDocument.Load(profileFile);
    foreach (var profileElement in xDocument.Descendants("Profile")  // Iterates through the collection of "Profile" elements
                                            .ToList())               // Copies the list (it's needed because we modify it in the foreach (when the element is removed)
    {
        if (profileElement.Attribute("Name").Value == profileName)   // Checks the name of the profile
        {
            profileElement.Remove();                                 // Removes the element
        }
    }
    xDocument.Save(profileFile);
}

如果只有一个空元素是因为您使用RemoveAll()(删除了元素的后代和属性)而不是Remove()(将其自身从父元素中删除).

If you have only an empty element is because you use RemoveAll() (removes the descendants and attributes of an element) instead of Remove() (removes the element it self from its parent).

您甚至可以通过在LINQ查询中将if替换为where来删除if:

You can even remove the if by replacing it by a where in the LINQ query:

foreach (var profileElement in (from profileElement in xDocument.Descendants("Profile")      // Iterates through the collection of "Profile" elements
                                where profileElement.Attribute("Name").Value == profileName  // Checks the name of the profile
                                select profileElement).ToList())                             // Copies the list (it's needed because we modify it in the foreach (when the element is removed)
    profileElement.Remove();  // Removes the element

xDocument.Save(profileFile);

这篇关于从XML文档中删除元素并保存旧文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆