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

后端 未结 2 648
既然无缘
既然无缘 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:22

    As you indicated that you are working with an XmlDocument, you need to remove a child XmlElement node via the RemoveChild method on the parent node:

        string xml = @"
            
                
                    The Walking Dead
                    Test Name
                    1239859895
                
                
                    The Walking Dead
                    
                        29893893893
                        test1
                        test
                    
                        
            
            ";
        // Initialize and load the XmlDocument
        var doc = new XmlDocument();
        doc.LoadXml(xml);
    
        // Delete all XmlElements named "isbn".
        var list = doc.DocumentElement.GetElementsByTagName("isbn").OfType().ToArray();
        foreach (var element in list)
        {
            var parent = element.ParentNode;
            if (parent != null)
                parent.RemoveChild(element);
        }
        var newXml = doc.OuterXml;
        Debug.WriteLine(newXml);
    

    And the output is:

    
    
      
        The Walking Dead
        Test Name
      
      
        The Walking Dead
        
          test1
          test
        
      
    
    

提交回复
热议问题