Serialize Object into/from XElement/XDocument

本文介绍如何使用C#中的XDocument和XElement类进行数据对象与XML之间的相互转换。通过具体示例,展示了如何序列化StudentInfo类到XDocument以及如何从XDocument反序列化回StudentInfo对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

XDocument and its relative class XElement are core classes of the Linq XML in .net 4.0. 

 

how to convert to and from data object with XElement is something that should be on the common knowledge to the C# developers.

 

here we will discuss with an example.

 

Suppose that we have a StudentInfo class, which is something like this :

 

 

    [Serializable]
    public class StudentInfo 
    {

        [XmlElement("Name")]
        public virtual string Name { get; set; }

        [XmlElement("Age")]
        public virtual int Age { get; set; }

    }

 

 

To Convert one data object to XDocument, you may do the following. 

 

public StudentInfo ConvertFromXDocument(XDocument state_)
{
                var studentInfo = state_.Element("StudentInfo");
                var serializer = new XmlSerializer(typeof(StudentInfo));

                var student = serializer.Deserialize(studentInfo.CreateReader()) as StudentInfo);
}
 

 

Which basically that you use the XmlSerializer and you call the Deserialize method with XElement.CreateReader() method

 

 

 

To serialize one data object to XDocument, you can do the following.

 

public XDocument ConvertToXDocument(StudentInfo student)
{
               using (var memoryStream = new MemoryStream())
                {
                    using (TextWriter streamwriter = new StreamWriter(memoryStream))
                    {
                        var serializer = new XmlSerializer(typeof(StudentInfo));
                        serializer.Serialize(streamwriter, student);
                        var xelement = XElement.Parse(Encoding.ASCII.GetString(memoryStream.ToArray()));
                        return new XDocument(xelement);
                    }
                }
}
 

Basically what it does is to use the MemoryStream as intermediate medium, which you first do is to Seralize to the MemoryStream with StreamWriter... by calling the XmlSerializer.Serialize method. and later you parse the content returned by the MemoryStream, and just by using the XElement.Parse method to return the XElement.

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值