.Net XmlSerializer 输出数据类型

发布于 2024-11-17 00:05:33 字数 833 浏览 2 评论 0原文

我有一个方法,它接受一个对象并将其转换为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蓬勃野心 2024-11-24 00:05:33

.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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文