Get XML String from XElement

You can use the WriteTo method of the XElement object to an XmlWriter and this can be created in ten different ways like by giving a filename or passing a stream as output or simply giving the StringBuilder to write to:


/// <summary>
/// Generates XML string from an XElement
/// summary>
/// <param name="xml">XElement source</param>
public string GetXmlString(XElement xml)
{
// could also be any other stream
StringBuilder sb = new StringBuilder();

// Initialize a new writer settings
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration
= true;
xws.Indent
= true;

using (XmlWriter xw = XmlWriter.Create(sb, xws))
{
// the actual writing takes place
xml.WriteTo(xw);
}

return sb.ToString();

}

It is important to know that the XElement already supports ToString which generates the same results as this code, but when you want to get something else, this could be a good start.


See further information in MSDN.

Author: Pouya Panahy

Microsoft certified DevOps engineer with passion in analysing, designing and implementing solutions for Azure Cloud with hands-on experience in security and quality assurence.

3 thoughts on “Get XML String from XElement”

  1. yοu аre іn reality a еxcеllent webmaster.

    The wеb sіte loading pace is incrediblе.
    It sοrt of feels that you are doing any unique trick.

    Also, The contents are maѕterwork. you've performed a fantastic process on this matter!
    Visit my website ipad3

  2. Hello, Nеat pоst. There is а problem ωіth your site in web explorеr, may check this?
    IE nonethеless is the market chіef аnd a goοd pοrtion of otheг people will
    leave out your magnіficent writing becаuse of this рroblem.
    Here is my web blogbilligste ipad

Leave a Reply