How to remove a XMLNode from XMLDocument occuring at multiple nested levels

后端 未结 2 650
既然无缘
既然无缘 2021-01-21 14:01

I have a XML which has a node which kind of gets repeated across multiple levels in the file using C#.

Example of the XML:


    

        
2条回答
  •  时光取名叫无心
    2021-01-21 14:09

    The easiest way is to use XDocument instead of XmlDocument. Use .Descendants() to find all Nodes of a specific name/type. Then .Remove() them.

    string xml = @"
         
             The Walking Dead
             Test Name
             1239859895
         
         
             The Walking Dead
             
                 29893893893
                 test1
                 test
             
                 
     ";
    
    XDocument xdoc = XDocument.Parse(xml);
    xdoc.Descendants("isbn").Remove();
    string result = xdoc.ToString();
    

    But if you want to go with XmlDocument use this code:

     XmlDocument xmldoc = new XmlDocument();
     xmldoc.LoadXml(xml);
     foreach (var node in new  List(xmldoc.GetElementsByTagName("isbn")
                                             .OfType()).Where(
                                             x => x.ParentNode != null))
     {
         node.ParentNode.RemoveChild(node);                      
     }
    
     string result = xmldoc.OuterXml;
    

提交回复
热议问题