代码之家  ›  专栏  ›  技术社区  ›  Bullines

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

  •  4
  • Bullines  · 技术社区  · 17 年前

    问候语!

    我有一个包含以下内容的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移到id为“C”的小节,结果是:

    <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”小节的最佳方式是什么?

    1 回复  |  直到 17 年前
        1
  •  4
  •   Stephan    17 年前

    您需要使用如下查询获取Foo第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);
    

    第一个查询将获得这两个部分,然后删除它们并将它们添加到树上的正确位置。

    这里有一个完整的解决方案:

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