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#中的XDocument和XElement类进行数据对象与XML之间的相互转换。通过具体示例,展示了如何序列化StudentInfo类到XDocument以及如何从XDocument反序列化回StudentInfo对象。
1301

被折叠的 条评论
为什么被折叠?



