How do I serialize an XML-serializable object to an XML fragment (no XML declaration nor namespace references in the root element)?
No. This will produce a valid xml document which includes the XML declaration and namespace references. I want a fragment only.
Canoehead
2010-05-04 19:49:40
+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
2010-05-04 19:58:09
+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
2010-05-05 10:06:35
+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
2010-05-04 20:02:46
+1 and accepted. Thanks! Works beautifully and no XmlDocument/XmlNode manipulations.
Canoehead
2010-05-05 11:11:40
+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
2010-06-18 21:07:27