2013-07-20 114 views
0

我要去上刪除父節點來實現,但是當它再次運行,發生異常時,似乎是解析錯誤C#刪除XML父節點保留爲空節點

下面是我原來的XML

<?xml version="1.0" encoding="UTF-8"?> 
<stock> 
    <brand name="Samsung"> 
     <product name="Galaxy S2"/> 
     <product name="Galaxy S3"/> 
     <product name="Galaxy S4"/> 
    </brand>  
    <brand name="iPhone"> 
     <product name="iPhone 4"/> 
     <product name="iPhone 5"/> 
    </brand> 
</stock> 

我的目標是要做到這一點:

<?xml version="1.0" encoding="UTF-8"?> 
<stock> 
    <brand name="Samsung"> 
     <product name="Galaxy S2"/> 
     <product name="Galaxy S3"/> 
     <product name="Galaxy S4"/> 
    </brand> 
</stock> 

下面是我使用的removeAll刪除()的結果;

<?xml version="1.0" encoding="UTF-8"?> 
<stock> 
    <brand name="Samsung"> 
     <product name="Galaxy S2"/> 
     <product name="Galaxy S3"/> 
     <product name="Galaxy S4"/> 
    </brand> 
    <brand/> 
</stock> 

下面是我的代碼

public bool deleteBrand(string brand) 
{ 
    bool result = false; 

    try 
    { 
     List<string> existingBrandName = getBrand(); 
     if (existingBrandName.Contains(brand)) 
     { 
      XDocument productList = load(); 

      var query = from positions in productList.Descendants("brand") 
         where (string)positions.Attribute("name").Value == brand 
         select positions; 

      XElement selectedBrand = query.ElementAt(0); 
      selectedBrand.RemoveAll(); 


      var emptyElements = from element in productList.Descendants("stock") 
           where element.IsEmpty 
           select element; 

      while (emptyElements.Any()) 
       emptyElements.Remove(); 

      productList.Save(path); 
      result = true; 
     } 
    } 
    catch (Exception ex) 
    { 
     Console.WriteLine(ex.ToString()); 
    } 


    return result; 
} 
+0

我看不出區別:預期和結果看起來一樣。 ??? –

+0

目前還不清楚你想要做什麼 - 而且你已經做得不那麼清晰了,因爲它沒有正確縮進你的XML。你只是想刪除除第一個以外的所有品牌元素?請*描述*你想達到什麼,真的很清楚。 –

+0

@JonSkeet我只是重新縮進XML。 –

回答

1

你需要做的事情emptyElementsbrand還有:

public bool deleteBrand(string brand) 
{ 
    bool result = false; 
    try 
    { 
     List<string> existingBrandName = getBrand(); 
     if (existingBrandName.Contains(brand)) 
     { 
      XDocument productList = load(); 
      var query = from positions in productList.Descendants("brand") 
         where (string)positions.Attribute("name").Value == brand 
         select positions; 
      XElement selectedBrand = query.ElementAt(0); 
      selectedBrand.RemoveAll(); 
      var toCheck = productList.Descendants("stock") 
            .Concat(productList.Descendants("brand")); 
      var emptyElements = from element in toCheck 
           where element.IsEmpty 
           select element; 
      while (emptyElements.Any()) 
       emptyElements.Remove(); 
      productList.Save(path); 
      result = true; 
     } 
    } 
    catch (Exception ex) 
    { 
     Console.WriteLine(ex.ToString()); 
    } 
    return result; 
} 
+0

您能否告訴我結合「股票」和「品牌」列表的用途或目的是什麼? –

+0

@RajuGujarati你可以將它們都刪除,這樣就可以除去似乎是你唯一問題的無用的''。 –

+0

如果我想刪除xml中顯示的產品,我需要列出哪些列表? –