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.


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)

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

Usage example:

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


        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