【问题标题】:linq to xml - remove wrapper nodelinq to xml - 删除包装节点
【发布时间】:2011-08-28 01:31:31
【问题描述】:

有没有办法删除一个包装了几个其他节点但保留包含节点的节点?

我需要删除“AreaImageCaption”的所有实例,但需要保留“image”和“caption”

<products>
    <product>
        <name>100</name>
        <AreaImageCaption>
            <image>image1</image>
            <caption>caption1</caption>
        </AreaImageCaption>
        <AreaImageCaption>
            <image>image2</image>
            <caption>caption2</caption>
        </AreaImageCaption>
    </product>
</products>

谢谢

【问题讨论】:

    标签: asp.net xml linq linq-to-xml


    【解决方案1】:

    试试这个

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

    我正在尝试从 &lt;AreaImageCaption /&gt; 添加所有子元素并将其添加到其父元素,然后删除 &lt;AreaImageCaption /&gt; 元素。

    【讨论】:

    • 这似乎有效。唯一的问题是原始 XML 文件在 AreaImageCaption 之后有更多节点,并且使用这种方法,所有图像和标题节点都将附加到 XML 文件的末尾,并且需要它们保持在相同的位置......有什么想法吗?
    • 我不确定如何保留订单。可能不是正确的做法,但你不能用 string.Empty 替换 &lt;AreaImageCaption&gt;&lt;/AreaImageCaption&gt; 吗?
    • 是的,这是我想到的第一件事,但它看起来不是最优雅的方法......我认为可能还有其他方法
    • 您可以在末尾插入如上所示,也可以在开头插入AddFirst()。还有我从未使用过的AddAfterSelf()。看看是不是你需要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多