.Net XmlSerializer Output Data Type
I have a method which takes an object and turns it into a string of XML. This works great but I want the output XML to include the data type of object properties (string, int, double, etc). I've searched high and low but I can't seem to find a solution without writing a custom serializer.
Any help would be most appreciated.
private static string ToXML<t>(t obj, bool indent = false)
{
System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces();
XmlSerializer xs = new XmlSerializer(typeof(t));
StringBuilder sbuilder = new StringBuilder();
var xmlws = new System.Xml.XmlWriterSettings() {OmitXmlDeclaration = true, Indent = indent};
ns.Add(string.Empty, string.Empty);
using (var writer = System.Xml.XmlWriter.Create(sbuilder, xmlws))
{
xs.Serialize(writer, obj, ns);
}
string result = sbuilder.ToString();
开发者_JAVA技巧 ns = null;
xs = null;
sbuilder = null;
xmlws = null;
return result;
}
The XmlSerializer
in .NET is designed to work with itself to re-serialize using the concrete object type to determine how it should treat the data from XML.
The standard XmlSerializer
will not serialize that information for you.
You should look into the DataContractSerializer
from WCF, from what I remember it's much more verbose and assumes less. It's also very flexible.
精彩评论