2009-05-29 7 views
4

인사말!LINQ to XML 초보자 : 한 노드에서 다른 노드로 노드 이동

:

<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> 

나는 결과가 같은 것을 "C"의 ID와 하위 섹션에 푸의 2와 3을 이동하려는 :

나는 다음이 포함 된 XElement를 개체가

<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"SubSection으로 이동하는 가장 좋은 방법은 무엇입니까? 그리고 단지에 추가

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

그리고 그 목록을 반복하고

xelem.Remove(); 

과 부모에서 제거 :

답변

4

당신은 같은 쿼리와 푸 2 항과 3 항을 얻을 필요 올바른 노드 :

parentElem.Add(xelem); 

첫 번째 쿼리는 두 섹션을 모두 가져와 각각을 제거하고 추가합니다. 나무에 올바른 장소. 당신의 xDoc 올바른 트리가 있어야 그 후

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); 
     } 

:

여기에 완벽한 솔루션입니다.

+0

몇 가지 사소한 의견 : .Value는 문자열이므로 "2"와 "3"을 인용하십시오. 난 당신이 대신 foos.Remove() iterating 대신 호출 할 수 있습니다 믿습니다. .Remove()가 foos를 정리하기 때문에 그 전에 foos를 복사해야 할 수도 있습니다. –

+0

아마도 맞을 것입니다. 아마도 foos.Remove()를 호출하고 parentElem.Add (foos)를 호출 할 수 있다고 상상했지만 iterate하는 것이 더 좋을 것이라고 생각한 다음 해당 요소를 제거하고 추가 한 다음 IEnumerable을 다음 요소로 이동합니다. . – Stephan

+0

빈 parentElem 노드가 생성됩니다. var toMove = foos; foos.Remove(); parentElem.Add (toMove); 그러면 웹 서버가 종료됩니다 (동일한 노드를 계속 추가하고 제거하기 때문에) : var toMove = foos; parentElem.Add (toMove); foos.Remove(); 아이디어가 있으십니까? – Bullines