Serialize Object into/from XElement/XDocument

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.

 

 

 

 

 

你可能感兴趣的:(C# xml)