开发者

remove xml nodes from xml document

开发者 https://www.devze.com 2022-12-27 05:01 出处:网络
I have a XMLDocument like: <Folder name=\"test\"> <Folder name=\"test2\"> <File>TestFile</File>

I have a XMLDocument like:

<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 A开发者_如何学编程LL elements in the document?

Thanks!


If you can use XDocument and LINQ, you can do

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 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消