如何删除文件的XML元素? [英] How to remove an xml element from file?

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

问题描述

在一个XML文件,如:

In an XML file such as :

<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");
}

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

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