تهیه خروجی XML از یک بانک اطلاعاتی، توسط EF Code first
نویسنده: وحید نصیری
تاریخ: ۱۳۹۲/۰۵/۱۰ ۱۱:۳۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace DNTViewer.Common.Toolkit
{
public static class Serializer
{
public static string Serialize<T>(T type)
{
var serializer = new XmlSerializer(type.GetType());
using (var stream = new MemoryStream())
{
serializer.Serialize(stream, type);
stream.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
}
} private string createXmlFile(string dir)
{
var xLinq = new XElement("ArrayOfPost",
_blogPosts
.AsNoTracking()
.Include(x => x.Comments)
.Include(x => x.User)
.Include(x => x.Tags)
.OrderBy(x => x.Id)
.ToList()
.Select(x => new XElement("Post", postXElement(x)))
);
var xmlFile = Path.Combine(dir, "dot-net-tips-database.xml");
xLinq.Save(xmlFile);
return xmlFile;
}
private static XElement[] postXElement(BlogPost x)
{
return new XElement[]
{
new XElement("Id", x.Id),
new XElement("Title", x.Title),
new XElement("Body", x.Body),
new XElement("CreatedOn", x.CreatedOn),
tagElement(x),
new XElement("User",
new XElement("Id", x.UserId.Value),
new XElement("FriendlyName", x.User.FriendlyName))
}.Where(item => item != null).ToArray();
}
private static XElement tagElement(BlogPost x)
{
var tags = x.Tags.Any() ?
x.Tags.Select(y =>
new XElement("Tag",
new XElement("Id", y.Id),
new XElement("Name", y.Name)))
.ToArray() : null;
if (tags == null)
return null;
return new XElement("Tags", tags);
}using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace DNTViewer.Common.Toolkit
{
public static class Serializer
{
public static T DeserializePath<T>(string xmlAddress)
{
using (var xmlReader = new XmlTextReader(xmlAddress))
{
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(xmlReader);
}
}
}
}