微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 如何从文件中删除一个xml元素?

一个 XML文件中,如:
<Snippets>
 <Snippet name="abc">
   <SnippetCode>
   code goes here
   </SnippetCode>
 </Snippet>

 <Snippet name="def">
   <SnippetCode>
   code goes here
   </SnippetCode>
 </Snippet>
</Snippets>

只有在给定属性名称(如abc或def)时,如何删除元素?

解决方法

你可以尝试这样的东西:
string xmlInput = @"<Snippets>
 <Snippet name=""abc"">
   <SnippetCode>
   code goes here
   </SnippetCode>
 </Snippet>

 <Snippet name=""def"">
   <SnippetCode>
   code goes here
   </SnippetCode>
 </Snippet>
</Snippets>";

// create the XML,load the contents
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlInput);

// find a node - here the one with name='abc'
XmlNode node = doc.SelectSingleNode("/Snippets/Snippet[@name='abc']");

// if found....
if (node != null)
{
   // get its parent node
   XmlNode parent = node.ParentNode;

   // remove the child node
   parent.RemoveChild(node);

   // verify the new XML structure
   string newXML = doc.OuterXml;

   // save to file or whatever....
   doc.Save(@"C:\temp\new.xml");
}

原文地址:https://www.jb51.cc/csharp/93447.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐