问题描述
您好!
我有一个包含以下内容的对象的XElement:
I have an XElement object that contains the following:
<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,这样的结果是:
I'd like to move Foo's 2 and 3 to the SubSection with the id of "C" such that the result is:
<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>
什么是去移动富段2的最佳途径,3到C款?
What's the best way to go about moving Foo sections "2" and "3" to the "C" SubSection?
推荐答案
您需要得到美孚第2和第3像查询:
You need to get Foo sections 2 and 3 with a query like:
var foos = from xelem in root.Descendants("Foo")
where xelem.Attribute("id").Value == "2" || xelem.Attribute("id").Value == "3"
select xelem;
然后遍历该列表,并从他们的父母将其删除
And then iterate that list and remove them from their parents with
xelem.Remove();
然后把它们添加到正确的节点有:
Then just add them to the correct node with:
parentElem.Add(xelem);
第一个查询将让你两部分然后删除和添加每一个到树的正确的位置。
The first query will get you both sections then remove and add each one to the correct place on the tree.
下面是一个完整的解决方案:
Here's a complete solution:
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有正确的树。
After that your xDoc should have the correct tree.
这篇关于LINQ到XML新手:移动节点从一个节点到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!