0

我将在删除父节点时实施,但是当它再次运行时,会发生异常并且似乎是解析错误

以下是我的原始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;
}
4

1 回答 1

1

您还需emptyElements要这样做brand

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;
}
于 2013-07-20T15:27:38.437 回答