How do you serialize a string as CDATA using XmlSerializer?

[Serializable] public class MyClass { public MyClass() { } [XmlIgnore] public string MyString { get; set; } [XmlElement(“MyString”)] public System.Xml.XmlCDataSection MyStringCDATA { get { return new System.Xml.XmlDocument().CreateCDataSection(MyString); } set { MyString = value.Value; } } } Usage: MyClass mc = new MyClass(); mc.MyString = “<test>Hello World</test>”; XmlSerializer serializer = new XmlSerializer(typeof(MyClass)); StringWriter writer = new … Read more

How can I make the xmlserializer only serialize plain xml?

To put this all together – this works perfectly for me: // To Clean XML public string SerializeToString<T>(T value) { var emptyNamespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty }); var serializer = new XmlSerializer(value.GetType()); var settings = new XmlWriterSettings(); settings.Indent = true; settings.OmitXmlDeclaration = true; using (var stream = new StringWriter()) using (var writer = XmlWriter.Create(stream, … Read more

How to serialize an object to XML without getting xmlns=”…”?

Ahh… nevermind. It’s always the search after the question is posed that yields the answer. My object that is being serialized is obj and has already been defined. Adding an XMLSerializerNamespace with a single empty namespace to the collection does the trick. In VB like this: Dim xs As New XmlSerializer(GetType(cEmploymentDetail)) Dim ns As New … Read more

.NET XML serialization gotchas? [closed]

Another huge gotcha: when outputting XML through a web page (ASP.NET), you don’t want to include the Unicode Byte-Order Mark. Of course, the ways to use or not use the BOM are almost the same: BAD (includes BOM): XmlTextWriter wr = new XmlTextWriter(stream, new System.Text.Encoding.UTF8); GOOD: XmlTextWriter wr = new XmlTextWriter(stream, new System.Text.UTF8Encoding(false)) You can … Read more

What is MyAssembly.XmlSerializers.dll generated for?

In .NET implementation, the XmlSerializer generates a temporary assembly for serializing/deserializing your classes (for performance reasons). It can either be generated on the fly (but it takes time on every execution), or it can be pregenerated during compilation and saved in this assembly you are asking about. You can change this behaviour in project options … Read more

XmlSerializer: remove unnecessary xsi and xsd namespaces

//Create our own namespaces for the output XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); //Add an empty namespace and empty value ns.Add(“”, “”); //Create the serializer XmlSerializer slz = new XmlSerializer(someType); //Serialize the object with our own namespaces (notice the overload) slz.Serialize(myXmlTextWriter, someObject, ns)