簡體   English   中英

從父級刪除所有子級節點,除了一個特定的C#中的xml

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

這是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>

我必須從每個行節點中刪除所有子節點,但我嘗試此方法的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();
    }
}

這是我期望的最終結果:

<ItemWarehouseInfo>
      <row>
        <WarehouseCode>Mc</WarehouseCode>
      </row>
      ...other equal lines
</ItemWarehouseInfo>
doc.Descendants("row").Elements().Where(e => e.Name != "WarehouseCode").Remove();

說明:

  • doc.Descendants("row") -查找所有行元素,無論它們有多深。

  • Elements() -獲取所有直接子元素

  • Where() -獲取名稱不是WarehouseCode所有元素

  • Remove() -刪除所有找到的元素

您無需為每一行都調用.Elements() ,您已經獲得了元素列表:

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

獲取行,將其刪除。 創建新行,添加該行的WarehouseCode,然后將該行添加到magaRow。 如果這不起作用,我懷疑名稱空間會引起問題。

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