score:2

Accepted answer

You could probably do this with LINQ, but it sounds like a regular old REGEX would be much, much better.

It sounds like this question, and particularly this answer demonstrate what you're trying to do.

score:1

If you want to do this exactly via LinqToXml, try something like this recursive function:

    static void ReplaceNodesWithContent(XElement element, string targetElementname)
    {
        if (element.Name == targetElementname)
        {
            element.ReplaceWith(element.Value);
            return;
        }

        foreach (var child in element.Elements())
        {
            ReplaceNodesWithContent(child, targetElementname);
        }
    }

Usage example:

    static void Main(string[] args)
    {
        string xml = @"<root>
<items>
    <item>
        <a>inner</a>
    </item>
    <item>
        <subitem>
            <a>another one</a>
        </subitem>
    </item>
</items>

";

        XElement x = XElement.Parse(xml);

        ReplaceNodesWithContent(x, "a");

        string res = x.ToString();
        //            res == @"<root>
        //                      <items>
        //                        <item>inner</item>
        //                        <item>
        //                          <subitem>another one</subitem>
        //                        </item>
        //                      </items>
        //                    </root>"
    }

Related Articles