将数据从任何类型转换为XML的通用解决方案 [英] Generic solution to convert data from any type to XML

查看:76
本文介绍了将数据从任何类型转换为XML的通用解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个实用程序类库,可以在任何项目中引用其dll。类库将具有将对象数据类型数据作为输入参数并将其转换为XML文件并将其存储在文件路径中的方法。



方法应该接受对象数据类型(对象数据类型可以类似于任何类型的数据,即用户定义的数据类型或类的对象,列表,数据表,JSON格式等)



我尝试过:



我创建了这个方法,它为 datatable <返回了正确的结果/ code>和列表但是 JSON 数据类型失败:

< pre lang =c#> public static string GetXMLFromObject( object o)
{
StringWriter sw = new StringWriter( );
XmlTextWriter tw = null ;
尝试
{
XmlSerializer serializer = new XmlSerializer(o。的GetType());
tw = new XmlTextWriter(sw);
serializer.Serialize(tw,o);
}
catch (例外情况)
{
throw ex;
// 处理例外代码
}
最后
{
sw.Close();
if (tw!= null
{
tw。关();
}
}
return sw.ToString();
}





任何线索都会受到高度赞赏。

解决方案

< blockquote>你应该使用 JSON序列化 [ ^ ]用于JSON数据而不是 XmlSerialization



详情请见:如何:序列化和反序列化JSON数据Microsoft Docs [ ^ ]


This is a utility class library whose dll can be referenced in any project. The class library will have methods which will take object data type data as input parameter and convert it to a XML file and store it in a file path.

Method should accept object data type (Object data type can resemble data of any type, i.e., user defined data type or object of a class, list, data table, JSON format, etc.)

What I have tried:

I have created this method which is returning proper result for datatable and list but failing for JSON data type:

public static string GetXMLFromObject(object o)
        {
            StringWriter sw = new StringWriter();
            XmlTextWriter tw = null;
            try
            {
                XmlSerializer serializer = new XmlSerializer(o.GetType());
                tw = new XmlTextWriter(sw);
                serializer.Serialize(tw, o);
            }
            catch (Exception ex)
            {
                throw ex;
                //Handle Exception Code
            }
            finally
            {
                sw.Close();
                if (tw != null)
                {
                    tw.Close();
                }
            }
            return sw.ToString();
        }



Any leads would be highly appreciated.

解决方案

You should use JSON serialization[^] for JSON data instead of XmlSerialization.

For further details, please see: How to: Serialize and Deserialize JSON Data | Microsoft Docs[^]


这篇关于将数据从任何类型转换为XML的通用解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆