Search code examples
c#xmldocumentxelement

Remove Child Nodes Keep Their Parent


I have XML Code Block as below (it is part of similar lines of hundreds..):

<specs>
    <spec name='fald' value = '100'>
        <name></name>
        <value></value>
    </spec>
</specs>

I need to convert code as seen below:

  <specs>
     <spec name ='fald' value = '100'/>
  </specs>

Using following code I am able to delete child nodes:

foreach (XElement child in doc.Descendants().Reverse())
{
    if (child.HasAttributes)
    {
        foreach (var attribute in child.Attributes())
        {
            if (string.IsNullOrEmpty(attribute.Value) && string.IsNullOrEmpty(child.Value))
                child.Remove();
        }
    }
}

But this process also deletes parent node ('spec') which is expected to take place there. Any help is appreciated, thanks...


Solution

  • It's a little unclear what the criteria for deleting an element is, but to get you started, perhaps this is somewhere along the lines of what you are looking for?

    var xml =
        @"<specs>
            <spec name='fald' value='100'>
              <name></name>
              <value></value>
            </spec>
          </specs>";
    
    var doc = XElement.Parse(xml);
    
    var childrenToDelete = doc.XPathSelectElements("//spec/*")
        .Where(elem => string.IsNullOrEmpty(elem.Value)
                && (!elem.HasAttributes
                || elem.Attributes().All(attr => string.IsNullOrEmpty(attr.Value))))
        .ToList();
    
    foreach (var child in childrenToDelete)
    {
        child.Remove();
    }
    
    // Produces:
    // <specs>
    //   <spec name="fald" value="100" />
    // </specs>
    

    Check this fiddle for a test run.