.Net XmlSerializer 输出数据类型
我有一个方法,它接受一个对象并将其转换为 XML 字符串。这很好用,但我希望输出 XML 包含对象属性的数据类型(字符串、整数、双精度等)。我到处搜索,但如果不编写自定义序列化程序,我似乎无法找到解决方案。
任何帮助将不胜感激。
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();
ns = null;
xs = null;
sbuilder = null;
xmlws = null;
return result;
}
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();
ns = null;
xs = null;
sbuilder = null;
xmlws = null;
return result;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
.NET 中的
XmlSerializer
旨在与自身一起使用具体对象类型进行重新序列化,以确定应如何处理 XML 中的数据。标准
XmlSerializer
不会为您序列化该信息。您应该查看 WCF 中的 DataContractSerializer,据我所知,它更加冗长并且假设更少。它也非常灵活。
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.