从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>TemplatesTemplate1.htm</mailBodyPath>
    </settings>
 </config>

在实践中,我只需要删除所有标签"mailCC"。我目前正在尝试这个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);
}

你能帮我吗?

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

XmlNodeList xnList = xml.GetElementsByTagName("mailCC");
while (xnList.Count > 0) {
    xnList[0].ParentNode.RemoveChild(xnList[0]);
}

使用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
}

相关内容

  • 没有找到相关文章

最新更新