Thursday, April 21, 2011

Serialize into an XML Fragment - not XML Document

How do I serialize an XML-serializable object to an XML fragment (no XML declaration nor namespace references in the root element)?

From stackoverflow
  • Hi Canoehead,

    How to serialize an object to XML by using Visual C#

    Canoehead : No. This will produce a valid xml document which includes the XML declaration and namespace references. I want a fragment only.
  • You should be able to just serialize like you usually do, and then use the Root property from the resulting document.

    You may need to clear the attributes of the element first.

    Canoehead : +1 Sounds good to me but what I didn't explain in my question was that I'd prefer to produce a stream and not an XmlDocument.
  • Here is a hack-ish way to do it without having to load the entire output string into an XmlDocument:

    using System;
    using System.Text;
    using System.Xml;
    using System.Xml.Serialization;
    
    public class Example
    {
        public String Name { get; set; }
    
        static void Main()
        {
            Example example = new Example { Name = "Foo" };
    
            XmlSerializer serializer = new XmlSerializer(typeof(Example));
    
            XmlSerializerNamespaces emptyNamespace = new XmlSerializerNamespaces();
            emptyNamespace.Add(String.Empty, String.Empty);
    
            StringBuilder output = new StringBuilder();
    
            XmlWriter writer = XmlWriter.Create(output,
                new XmlWriterSettings { OmitXmlDeclaration = true });
            serializer.Serialize(writer, example, emptyNamespace);
    
            Console.WriteLine(output.ToString());
        }
    }
    
    Canoehead : +1 and accepted. Thanks! Works beautifully and no XmlDocument/XmlNode manipulations.
    Jim Leonardo : +1 - I don't think it's really hackish at all. Maybe more set up work than I'd like to do. But, at the end, it's telling it what format the output should be before it does the work. That's not a hack. A hack would be to strip everything out after the fact etc.

0 comments:

Post a Comment