none
Object to XElement RRS feed

  • Question

  • Hi all,

    I have an object that I need to serialize it to XML and store it to a SQL Server database with XML as the column type.

    I am wondering if there is a way that I can seriaize it directly from the object to XElement as the Linq to SQL generator treat that field as an XElement object.

    What I am doing now is that I am using the XmlSerializer to serialize the object into a stream and then use XDocument.Load and pass in the XmlTextReader.
    Is there a more efficent way to accomplish this?

    thanks a lot,

    Gasnic

    Monday, August 10, 2009 9:01 PM

Answers

  • It could be more efficient to serialize to an XmlWriter created from the CreateWriter method of an XDocument instance and then take the Root element XElement:

        class Program
        {
            static void Main(string[] args)
            {
                Foo foo = new Foo() { Bar = "a", Baz = 1 };
                XmlSerializer ser = new XmlSerializer(typeof(Foo));
                XDocument doc = new XDocument();
                using (XmlWriter xw = doc.CreateWriter())
                {
                    ser.Serialize(xw, foo);
                    xw.Close();
                }
                XElement el = doc.Root;
                Console.WriteLine(el);
                
            }
        }
    
        public class Foo
        {
            public string Bar { get; set; }
            public int Baz { get; set; }
        }

    MVP XML My blog
    • Marked as answer by gasnic Tuesday, August 11, 2009 1:49 PM
    Tuesday, August 11, 2009 11:26 AM

All replies

  • It could be more efficient to serialize to an XmlWriter created from the CreateWriter method of an XDocument instance and then take the Root element XElement:

        class Program
        {
            static void Main(string[] args)
            {
                Foo foo = new Foo() { Bar = "a", Baz = 1 };
                XmlSerializer ser = new XmlSerializer(typeof(Foo));
                XDocument doc = new XDocument();
                using (XmlWriter xw = doc.CreateWriter())
                {
                    ser.Serialize(xw, foo);
                    xw.Close();
                }
                XElement el = doc.Root;
                Console.WriteLine(el);
                
            }
        }
    
        public class Foo
        {
            public string Bar { get; set; }
            public int Baz { get; set; }
        }

    MVP XML My blog
    • Marked as answer by gasnic Tuesday, August 11, 2009 1:49 PM
    Tuesday, August 11, 2009 11:26 AM
  • How can we keep the attributes from showing up in the .doc.Root element?
    Thursday, January 19, 2012 3:26 AM