Reputation: 139
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
Reputation: 7142
doc.Descendants("row")
.Elements()
.Where(e => e.Name != "WarehouseCode")
.Remove();
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
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
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