LINQ to XML新手:将节点从一个节点移动到另一个节点

问题描述:

问候!LINQ to XML新手:将节点从一个节点移动到另一个节点

我有一个包含以下内容的的XElement对象:

<Root> 
    <SubSections> 
     <SubSection id="A"> 
      <Foo id="1"> 
       <Bar /> 
       <Bar /> 
       <Bar /> 
      </Foo> 
      <Foo id="2"> 
       <Bar /> 
       <Bar /> 
      </Foo> 
      <Foo id="3"> 
       <Bar /> 
      </Foo> 
     </SubSection> 
     <SubSection id="B"> 
      <Foo id="4"> 
       <Bar /> 
       <Bar /> 
       <Bar /> 
      </Foo> 
      <Foo id="5"> 
       <Bar /> 
       <Bar /> 
      </Foo> 
     </SubSection> 
     <SubSection id="C"> 

     </SubSection> 
    </SubSections> 
</Root> 

我想Foo的2和3移动到第同的“C”的ID,使得结果是:

<Root> 
    <SubSections> 
     <SubSection id="A"> 
      <Foo id="1"> 
       <Bar /> 
       <Bar /> 
       <Bar /> 
      </Foo> 
     </SubSection> 
     <SubSection id="B"> 
      <Foo id="4"> 
       <Bar /> 
       <Bar /> 
       <Bar /> 
      </Foo> 
      <Foo id="5"> 
       <Bar /> 
       <Bar /> 
      </Foo> 
     </SubSection> 
     <SubSection id="C"> 
      <Foo id="2"> 
       <Bar /> 
       <Bar /> 
      </Foo> 
      <Foo id="3"> 
       <Bar /> 
      </Foo> 
     </SubSection> 
    </SubSections> 
</Root> 

什么是将Foo段“2”和“3”移动到“C”子段的最佳方式?

你需要得到美孚第2和第3像查询:

var foos = from xelem in root.Descendants("Foo") 
      where xelem.Attribute("id").Value == "2" || xelem.Attribute("id").Value == "3" 
      select xelem; 

然后遍历该列表,并从他们的父母

xelem.Remove(); 

删除它们然后把它们添加到正确的节点与:

parentElem.Add(xelem); 

第一个查询会让你两个部分然后删除并添加每个t o树上的正确位置。

下面是一个完整的解决方案:

var foos = (from xElem in xDoc.Root.Descendants("Foo") 
        where xElem.Attribute("id").Value == "2" || xElem.Attribute("id").Value == "3" 
        select xElem).ToList(); 

     var newParentElem = (from xElem in xDoc.Root.Descendants("SubSection") 
          where xElem.Attribute("id").Value == "C" 
          select xElem).Single(); 

     foreach(var xElem in foos) 
     { 
      xElem.Remove(); 
      newParentElem.Add(xElem); 
     } 

,你应该XDOC有正确的树后。

+0

一些小的评论:.Value是一个字符串,所以引用“2”和“3”。我相信你可以调用foos.Remove()而不是迭代。虽然您可能需要在此之前复制foos,因为.Remove()会清除foos。 – 2009-05-29 19:12:01