简体   繁体   English

从父级删除所有子级节点,除了一个特定的C#中的xml

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

This is Xml 这是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: 我必须从每个行节点中删除所有子节点,但我尝试此方法的WarehouseCode节点除外,但是显然我错了,没有任何变化:

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

Explanation: 说明:

  • doc.Descendants("row") - Finds all row elements no matter how deep they are. doc.Descendants("row") -查找所有行元素,无论它们有多深。

  • Elements() - Gets all immediate children elements Elements() -获取所有直接子元素

  • Where() - Gets all elements whose name is not WarehouseCode Where() -获取名称不是WarehouseCode所有元素

  • Remove() - Deletes all found elements Remove() -删除所有找到的元素

You don't need to call .Elements() for each row, you already got the list of elements: 您无需为每一行都调用.Elements() ,您已经获得了元素列表:

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

Get row, remove it. 获取行,将其删除。 Create new row, add the row's WarehouseCode, and then add that row to the magaRow. 创建新行,添加该行的WarehouseCode,然后将该行添加到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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM