c#如何将Object转换为XML

时间:2014-05-19 08:43:36

标签: c# silverlight serialization xml-serialization silverlight-5.0

我是c#和silverlight 5初学者。我必须向银色高级开发人员明确表示怀疑。

我在c#中有一个对象,我必须获取与该对象相对应的xml。

有人可以通过一个例子解释如何做到这一点(任何类的简单例子及其对象然后获得xml)

我在google上阅读了一些文档,他们讨论了一些能够这样做的方法调用serialize()。我对吗 ?但它是如何做的可以请一些人通过c#类解释它的对象和xml获得?

将是一个很大的帮助。 编辑: 我的尝试是:

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml.Serialization;
using System.IO;
using System.Text;

namespace SliderLastTry
{
    public static class Xml
    {
        public static string ToXml(this object objectToSerialize)
        {
            var mem = new MemoryStream();
            var ser = new XmlSerializer(objectToSerialize.GetType());
            ser.Serialize(mem, objectToSerialize);
            var utf8 = new UTF8Encoding();
            return utf8.GetString(mem.ToArray());
        }
    }
}

下一节课是:

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SliderLastTry
{
    public  class Parameter 
    { 
        public  string Name {get; set; } 
    }  
}

包含类的Main函数是:

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SliderLastTry
{
    public static class ControlClass
    {
        public static void Main()
        {
            Parameter pram = new Parameter();
            pram.ToXml();

        }

    }
}

获得的错误是:

Error   1   'System.Text.Encoding.GetString(byte[])' is inaccessible due to its protection level 

对应线/

return utf8.GetString(mem.ToArray()); in Xml class. How toma the solution of it ?

2 个答案:

答案 0 :(得分:2)

var writer = new StringWriter();
var serializer = new XmlSerializer(typeof(YourData));
serializer.Serialize(writer, obj);
string xml = writer.ToString();

See also MSDN

答案 1 :(得分:1)

我使用这个类

public static class Xml
{
    public static string ToXml(this object objectToSerialize)
    {
        var mem = new MemoryStream();
        var ser = new XmlSerializer(objectToSerialize.GetType());
        ser.Serialize(mem, objectToSerialize);
        var utf8 = new UTF8Encoding();
        return utf8.GetString(mem.GetBuffer(), 0, (int)mem.Length);
    }
}

使用此扩展方法,您可以

var xml = your_object.ToXml();