2011-05-18 71 views
1

是否有办法删除包装其他几个节点但保留包含节点的节点?linq to xml - 删除包装节点

我需要删除 “AreaImageCaption” 的所有实例,但需要保持 “形象” 和 “标题”

<products> 
    <product> 
     <name>100</name> 
     <AreaImageCaption> 
      <image>image1</image> 
      <caption>caption1</caption> 
     </AreaImageCaption> 
     <AreaImageCaption> 
      <image>image2</image> 
      <caption>caption2</caption> 
     </AreaImageCaption> 
    </product> 
</products> 

感谢

回答

0

试试这个

 string s = 
      @"<products> 
     <product> 
      <name>100</name> 
      <AreaImageCaption> 
       <image>image1</image> 
       <caption>caption1</caption> 
      </AreaImageCaption> 
      <AreaImageCaption> 
       <image>image2</image> 
       <caption>caption2</caption> 
      </AreaImageCaption> 
     </product> 
    </products>"; 

     XElement element = XElement.Parse(s); 
     element.Descendants("AreaImageCaption").ToList().ForEach(aic => 
                   { 
                    aic.Elements().ToList().ForEach(el => aic.Parent.Add(el)); 
                    aic.Remove(); 
                   }); 

     string result = element.ToString(); 

我m尝试添加<AreaImageCaption />中的所有子元素并将其添加到它的父级,然后删除<AreaImageCaption />元素。

+0

似乎工作。唯一的问题是原始XML文件在AreaImageCaption之后有更多的节点,并且通过这种方法,所有图像和标题节点都将附加到XML文件的末尾,并且需要它们保持在同一位置。有任何想法吗? – user441365 2011-05-18 13:32:30

+0

我不知道如何保持订单。可能不是正确的做法,但不能用string.Empty替换''和''? – 2011-05-18 13:34:40

+0

是的,这是我想到的第一件事,但它看起来并不像最优雅的方法......我想可能有其他的方式 – user441365 2011-05-18 13:40:47