.net/C# – Serialize into an XML Fragment – not XML Document – Stack Overflow
Posted by jpluimers on 2014/04/17
Thanks User Andrew Hare – Stack Overflow for answering this on Stack Overflow.
I’m pretty sure it works in all .NET and C# versions starting with 2.0.
Here is a hack-ish way to do it without having to load the entire output string into an XmlDocument:
[sourcecode language=”csharp”]
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());
}
}
[/sourcecode]
–jeroen via: .net – Serialize into an XML Fragment – not XML Document – Stack Overflow.






Leave a Comment