Search code examples
c#linqlinq-to-xmlxmlnode

Delete outer xml node without deleting inner xml


This is my xml:

<application name="Test Tables">
<test>
  <xs:schema id="test" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">   
  </xs:schema> 
</test>
</application>

How can I delete the <application> node without deleting the <test> node ?


Solution

  • OK, so probably not my best answer, but hoping either this fits your need, or gives you a a good starting point. Firstly, I'm assuming that you're using C#. So, the way I did this, was to use the node you want to remove and select its child nodes and use them to create a new XDocument. There could be a neater way using Linq to achieve this, but I'm damned if I can see it! Anyway, hope this helps :

    var doc = XDocument.Load(@".\Test1.xml");
    
    var q = (from node in doc.Descendants("application")
            let attr = node.Attribute("name")
            where attr != null && attr.Value == "Test Tables"
            select node.DescendantNodes()).Single();
    
    var doc2 =  XDocument.Parse(q.First().ToString());
    

    I used this SO post as my guide : How to delete node from XML file using C#

    Happy coding,
    Cheers,
    Chris.