Recently i faced a problem where i needed to get the InnerXml and the OuterXml of an XElement object. The solution was easy to find on the InnerXMl method but the OuterXml method was a bit harder. Here is what i have done.

Being used to use the XmlDocument class i recently faced the problem of first loading my XElement from a string, then getting the OuterXml and then the InnerXml of my XElement. The sloution proved to be straightforward, but i spend several minutes googling the solution anyway.

Loading a XElement from a string containing XML:

XElement element = XElement.Parse("<root></root>");

Concering getting the OuterXml and the InnerXml the solution is best done in a couple of extension methods, just add the below class to your project.

public static class MyExtensionClasses
{
    public static string OuterXml(this XElement thiz)
    {
        var xReader = thiz.CreateReader();
        xReader.MoveToContent();
        return xReader.ReadOuterXml();            
    }

    public static string InnerXml(this XElement thiz)
    {
        var xReader = thiz.CreateReader();
        xReader.MoveToContent();
        return xReader.ReadInnerXml();            
    }
}

Having added this to your project lets you access the OuterXml and the InnerXml in the following way:

XElement myElement = XElement.Parse("<root></root>");
string outerXml = myElement.OuterXml(); //You can do this because the methods are made as extension methods.

Hope you can use this and that it saves you a lot of agony and searching on the Internet.