Created
November 29, 2011 22:34
-
-
Save azcoov/1406901 to your computer and use it in GitHub Desktop.
ObjectToXElement
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.Xml; | |
using System.Xml.Linq; | |
using System.Xml.Serialization; | |
public static class GenericExtensions | |
{ | |
public static XElement ToXElement<T>(this T obj) | |
{ | |
try | |
{ | |
var emptyNamespace = new XmlSerializerNamespaces(); | |
emptyNamespace.Add(String.Empty, String.Empty); | |
var xmlSerializer = new XmlSerializer(typeof(T)); | |
var writerSettings = new XmlWriterSettings {OmitXmlDeclaration = true}; | |
var stringWriter = new StringWriter(); | |
using (var xmlWriter = XmlWriter.Create(stringWriter, writerSettings)) | |
{ | |
xmlSerializer.Serialize(xmlWriter, obj, emptyNamespace); | |
} | |
return XElement.Parse(stringWriter.ToString()); | |
} | |
catch (Exception) | |
{ | |
return null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment