c#如何将Object转换为XML
本文关键字:转换 XML Object | 更新日期: 2023-09-27 18:04:12
我是c#和silverlight 5的初学者。我必须向silverlight的资深开发人员澄清一个重要的疑问。
我在c#中有一个对象,我必须获得与该对象对应的xml。
有人能通过一个例子来解释如何做到这一点吗(类及其对象的任何简单例子,然后获得xml(
我在谷歌上读了一些文档,他们讨论了一些名为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; }
}
}
包含类的主要函数是:
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 ?
var writer = new StringWriter();
var serializer = new XmlSerializer(typeof(YourData));
serializer.Serialize(writer, obj);
string xml = writer.ToString();
另请参阅MSDN
我使用这个类
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();