c# – 如何从文件中删除一个xml元素?
发布时间:2020-12-15 03:54:08 所属栏目:百科 来源:网络整理
导读:在一个 XML文件中,如: Snippets Snippet name="abc" SnippetCode code goes here /SnippetCode /Snippet Snippet name="def" SnippetCode code goes here /SnippetCode /Snippet/Snippets 只有在给定属性名称(如abc或def)时,如何删除元素? 解决方法 你可以
在一个
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:tempnew.xml"); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |