r.pezzolati
r.pezzolati

Reputation: 139

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>

Upvotes: 1

Views: 2496

Answers (3)

JohnyL
JohnyL

Reputation: 7142

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

Upvotes: 3

Chuck Savage
Chuck Savage

Reputation: 11955

Get row, remove it. Create new row, add the row's WarehouseCode, and then add that row to the magaRow. If this doesn't work, I suspect namespaces are causing issues.

XElement row = magaRow.Element("row");
row.Remove();
XElement newRow = new XElement("row");
newRow.Add(row.Element("WarehouseCode"));
magaRow.Add(newRow);

Upvotes: 0

icebat
icebat

Reputation: 4774

You don't need to call .Elements() for each row, you already got the list of elements:

foreach(XElement child in row)
{
    if (child.Name != "WarehouseCode")
    {
        child.Remove();
    }
}

Upvotes: 0

Related Questions