您的位置:首页 > 编程语言 > C#

C#序列化匿名对象为XML

2015-12-24 22:27 507 查看
封装xml序列化类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace Xml.Utils
{
/// <summary>
/// 匿名对象序列化为XML
/// </summary>
public static class XmlTools
{
//识别需要序列化的类型
private static readonly Type[] WriteTypes = new[] {
typeof(string), typeof(DateTime), typeof(Enum),
typeof(decimal?), typeof(Guid),typeof(int?)
};
public static bool IsSimpleType(this Type type)
{
return type.IsPrimitive || WriteTypes.Contains(type);
}
public static XElement ToXml(this object input)
{
return input.ToXml(null);
}
public static XElement ToXml(this object input, string element)
{
if (input == null)
return null;
if (string.IsNullOrEmpty(element))
element = "object";
element = XmlConvert.EncodeName(element);
var ret = new XElement(element);
if (input != null)
{
var type = input.GetType();
var props = type.GetProperties();
var elements = from prop in props
let name = XmlConvert.EncodeName(prop.Name)
let val = prop.GetValue(input, null)
let value = prop.PropertyType.IsSimpleType()
? new XElement(name, val)
: val.ToXml(name)
where value != null
select value;
ret.Add(elements);
}
return ret;
}
}
}
待序列化匿名对象
var entityuser = (from u in db.User
where u.username == username
select new
{
id = u.id,
username = u.username,
email = u.email,
}).FirstOrDefault();
测试序列化匿名对象
entityuser.ToXml(); //使用方法,生成默认根节点名称xml
entityuser.ToXml("user"); //生成自定义根节点名称xml

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: