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();
과 부모에서 제거 :
몇 가지 사소한 의견 : .Value는 문자열이므로 "2"와 "3"을 인용하십시오. 난 당신이 대신 foos.Remove() iterating 대신 호출 할 수 있습니다 믿습니다. .Remove()가 foos를 정리하기 때문에 그 전에 foos를 복사해야 할 수도 있습니다. –
아마도 맞을 것입니다. 아마도 foos.Remove()를 호출하고 parentElem.Add (foos)를 호출 할 수 있다고 상상했지만 iterate하는 것이 더 좋을 것이라고 생각한 다음 해당 요소를 제거하고 추가 한 다음 IEnumerable을 다음 요소로 이동합니다. . – Stephan
빈 parentElem 노드가 생성됩니다. var toMove = foos; foos.Remove(); parentElem.Add (toMove); 그러면 웹 서버가 종료됩니다 (동일한 노드를 계속 추가하고 제거하기 때문에) : var toMove = foos; parentElem.Add (toMove); foos.Remove(); 아이디어가 있으십니까? – Bullines