【发布时间】:2015-07-15 00:00:15
【问题描述】:
*编辑:好的,所以我要删除程序,foreach (var elem in doc.Document.Descendants("Profiles")) 行需要“配置文件”。但是现在在我的 XML 文档中,每个删除的配置文件元素都有一个空的配置文件元素,所以如果 xml 示例中的所有项目(在问题的底部)都被删除,我只剩下这个:*
<?xml version="1.0" encoding="utf-8"?>
<Profiles>
<Profile />
<Profile />
</Profiles>
==========================下面的原始问题=================== ===============
我正在使用以下代码从 XML 文件中删除一个元素及其子元素,但它不会在保存时从文件中删除它们。有人可以告诉我为什么这是不正确的吗?
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>
【问题讨论】:
-
您是否尝试过调试它并确保首先删除了元素?也许没有删除任何内容,而您只是再次重新保存了相同的文件?
-
这就是我认为/正在发生的事情,我只是对 XML 不够熟悉,不知道我是否在适当地进行删除。我会再次调试,看看我能扣除什么,但我也会从问题中的 xml 中抛出一个示例,以防社区清楚这里有什么问题。
标签: c# xml linq-to-xml