Search code examples
c#xmllinq

Remove all child nodes from the parent except one specific, an xml in c #


This is Xml

 <ItemWarehouseInfo>
      <row>
        <MinimalStock>0.000000</MinimalStock>
        <MaximalStock>0.000000</MaximalStock>
        <MinimalOrder>0.000000</MinimalOrder>
        <StandardAveragePrice>0.000000</StandardAveragePrice>
        <Locked>tNO</Locked>
        <WarehouseCode>Mc</WarehouseCode>
        <DefaultBinEnforced>tNO</DefaultBinEnforced>
      </row>
      ...other equal lines
    </ItemWarehouseInfo>

I have to remove all child nodes from every row node except for the WarehouseCode node I tried this method but obviously I'm wrong and nothing changes:

    XDocument xdoc = XmlHelper.LoadXDocFromString(xmlOITM);
XElement magaRow = xdoc.Root.Descendants(Constants.Articoli.ART_MAGA_NODES).FirstOrDefault();//ItemWarehouseInfo node
List<XElement> row = magaRow.Elements().ToList();//row node
foreach(XElement child in row.Elements())
{
    if (child.Name != "WarehouseCode")
    {
        child.Remove();
    }
}

This is the final result that I expect:

<ItemWarehouseInfo>
      <row>
        <WarehouseCode>Mc</WarehouseCode>
      </row>
      ...other equal lines
</ItemWarehouseInfo>

Solution

  • doc.Descendants("row")
       .Elements()
       .Where(e => e.Name != "WarehouseCode")
       .Remove();
    

    Explanation:

    • doc.Descendants("row") - Finds all row elements no matter how deep they are.

    • Elements() - Gets all immediate children elements

    • Where() - Gets all elements whose name is not WarehouseCode

    • Remove() - Deletes all found elements