2009-05-29 107 views
4

問候!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」子段的最佳方式?

回答

4

你需要得到美孚第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

相關問題