开发者

linq to xml - remove wrapper node

is there a way to remove a node that is wrapping a few other nodes, but keeping the containing nodes?

I need to remove all the instances of "AreaImageCaption", but need to keep "image" and "caption"

<products>
    <product>
开发者_如何学编程        <name>100</name>
        <AreaImageCaption>
            <image>image1</image>
            <caption>caption1</caption>
        </AreaImageCaption>
        <AreaImageCaption>
            <image>image2</image>
            <caption>caption2</caption>
        </AreaImageCaption>
    </product>
</products>

Thanks


Try this

        string s =
            @"<products>
        <product>
            <name>100</name>
            <AreaImageCaption>
                <image>image1</image>
                <caption>caption1</caption>
            </AreaImageCaption>
            <AreaImageCaption>
                <image>image2</image>
                <caption>caption2</caption>
            </AreaImageCaption>
       </product>
    </products>";

        XElement element = XElement.Parse(s);
        element.Descendants("AreaImageCaption").ToList().ForEach(aic =>
                                                                 {
                                                                     aic.Elements().ToList().ForEach(el => aic.Parent.Add(el));
                                                                     aic.Remove();
                                                                 });

        string result = element.ToString();

I'm trying to add all child elements from <AreaImageCaption /> and add it to it's parent and then remove the <AreaImageCaption /> element.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜