简体   繁体   English

从xml文档中删除xml节点

[英]remove xml nodes from xml document

I have a XMLDocument like: 我有一个XMLDocument像:

<Folder name="test">
         <Folder name="test2">
              <File>TestFile</File>
         </Folder>
 </Folder>

I want only the folder´s, not the files. 我只想要文件夹,而不是文件。 So, how to delete / manipulate the XML Document in c# to delete / remove ALL elements in the document? 那么,如何在c#中删除/操作XML Document来删除/删除文档中的所有元素?

Thanks! 谢谢!

If you can use XDocument and LINQ, you can do 如果你可以使用XDocument和LINQ,你可以这样做

XDocument doc = XDocument.Load(filename) // or XDocument.Parse(string)
doc.Root.Descendants().Where(e => e.Name == "File").Remove();

-- edited out an error - 编辑出错误

To remove a node from an XMLDocument (see Jens' answer for remove node form XDocument ) XMLDocument中删除节点(请参阅Jens的删除节点表单XDocument的答案)

XmlDocument doc = XmlDocument.Load(filename); // or XmlDocument.LoadXml(string)
XmlNodeList nodes = doc.SelectNodes("//file");
foreach(XmlNode node in nodes) {
   node.ParentNode.RemoveChild(node);
}

Watch for the possible null exception if node.ParentNode is null. 如果node.ParentNode为null,请注意可能的null异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM