views:

207

answers:

3

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

A: 

Hi Canoehead,

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

Muse VSExtensions
No. This will produce a valid xml document which includes the XML declaration and namespace references. I want a fragment only.
Canoehead
+1  A: 

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.

Daniel Schaffer
+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.
Canoehead
+5  A: 

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());
    }
}
Andrew Hare
+1 and accepted. Thanks! Works beautifully and no XmlDocument/XmlNode manipulations.
Canoehead
+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.
Jim Leonardo