C#中将实体类转成XML
XML帮助类
[C#] 纯文本查看 复制代码 using System;
using System.Reflection;
using System.Xml.Linq;
namespace MyTool
{
public static class ObjectToXml
{
public static string Path
{
get { return String.Format(@"{0}/{1}.xml", Environment.CurrentDirectory,DateTime.Now.Day.ToString()); }
}
public static void Intit(object ob)
{
XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
new XElement("Data")); //建立跟节点 <Data></Data>
Process(ob,doc.Element("Data"));
doc.Save(Path);
}
private static void Process(object ob,XElement doc)
{
XElement data = doc;
string ClassName = ob.GetType().Name;
data.Add(new XElement(ClassName));//取类名 添加一个节点
PropertyInfo[] properties = ob.GetType().GetProperties(BindingFlags.Instance |BindingFlags.Public);
foreach (var item in properties)
{
string type = item.GetValue(ob).GetType().Name;
if (type.ToLower() == "string" || type.ToLower() == "int32" || type.ToLower() == "double")//判断属性是否是基本类型比如strin int double 若是,则建立节点并赋值
{
XElement ChildNode = data.Element(ClassName);
ChildNode.Add(new XElement(item.Name, item.GetValue(ob)));
}
else //否则,递归运行Process函数
{
Process(item.GetValue(ob), data.Element(ClassName));
}
}
}
}
}
实体类及调用方法
[C#] 纯文本查看 复制代码 using System;
using MyTool;
namespace xmltest
{
class Program
{
static void Main(string[] args)
{
var a = new student
{
Name = "memeda", age = 10,gg=1.5,
more=new info
{
boy="nan",
moreinfo=new moreinfo
{
mv="mv"
}
}
};
ObjectToXml.Intit(a);
Console.ReadKey();
}
}
public class student
{
public string Name { get; set; }
public int age { get; set; }
public double gg { get; set; }
public info more { get; set; }
}
public class info
{
public moreinfo moreinfo { get; set; }
public string boy { get; set; }
}
public class moreinfo
{
public string mv { get; set; }
}
}
|