从XML文件中删除列入XmlNodeList的节点

时间:2015-03-02 14:11:07

标签: c# xml xmlnodelist

我的XML文件存在问题。

 <?xml version="1.0" encoding="UTF-8"?>
   <config>
    <settings>
     <excelFilePath>C:\Temp\</excelFilePath>
     <mailHost>smtp</mailHost>
     <mailPort>25</mailPort>
     <mailFrom>me@test.com</mailFrom>
     <keepInCopy>
         <mailCC>email1@test.com</mailCC>
         <mailCC>email2@test.com</mailCC>
         <mailCC>email3@test.com</mailCC>
    </keepInCopy>
    <mailSubject>My Mail subject</mailSubject>
    <mailBodyPath>Templates\Template1.htm</mailBodyPath>
    </settings>
 </config>

在实践中,我只需要删除所有标签&#34; mailCC&#34;。 我目前正在尝试这个C#代码,但没有任何反应:

XmlDocument xml = new XmlDocument();
xml.Load(FilePath);

XmlNodeList xnList = xml.GetElementsByTagName("mailCC");
foreach (XmlNode xn in xnList)
{
    xn.RemoveChild(xn.FirstChild);
    xml.Save(FilePath);
}

你能帮我吗?

2 个答案:

答案 0 :(得分:1)

使用XmlDocument节点将从其父节点中删除。但你也可以这样做:

var xn = xml.SelectSingleNode("/config/settings/keepInCopy");
if (xn != null)
{
    xn.RemoveAll(); // Remove all "mailCC" elements, but keep "keepInCopy" node **OR**
    xn.ParentNode.RemoveChild(xn); // Remove "keepInCopy" element and all children
}

答案 1 :(得分:1)

删除节点将更新集合,因此不应使用foreach循环。

XmlNodeList xnList = xml.GetElementsByTagName("mailCC");

while (xnList.Count > 0) {
    xnList[0].ParentNode.RemoveChild(xnList[0]);
}