上篇随笔主要是针对于Xml的特性Attribute与实体之间的匹配与转换。该篇随笔主要内容为将对象转换成相应的Xml以及XElement。这2篇随笔以不同的方式对Xml进行转换与匹配,每种匹配都采用不同的角度进行操作。本文主要为对象实体的转换,下篇侧重于Xml的匹配。
二、Xml转换
2.1 实体集合转换Xml
实体集合转换Xml的方法为:public static string ToXml<T>(IList<T> entities, string rootName = "") where T : new(),通过传入的实体集合对象和Xml根名称,可以转换成相应的Xml,代码如下:
针对于实体集合的转换,转换后的结果如下:
2.2 实体转换Xml
实体转换Xml的方法为:public static string ToXml<T>(T entity) where T : new(),通过传入的实体,可以转换成相应的Xml,代码如下:
针对于单个实体的转换,转换后的结果如下:
2.3 实体集合转换XElement
实体转换XElement的方法为:public static XElement ToXElement<T>(IList<T> entities, string rootName = "") where T : new(),通过传入的实体集合对象和Xml根名称,可以转换成相应的XElement,代码如下:
2.4 实体集合转换XmlDocument
实体转换XmlDocument的方法为:public static XElement ToXmlDocument<T>(IList<T> entities, string rootName = "") where T : new(),通过传入的实体集合对象和Xml根名称,可以转换成相应的XmlDocument,代码如下:
2.5 实体转换XElement
实体转换XElement的方法为:public static string ToXElement<T>(T entity) where T : new(),通过传入的实体,可以转换成相应的XElement,代码如下:
2.6 实体集合转换XDocument
实体转换XDocument的方法为:public static XDocument ToXDocument<T>(IList<T> entities, string rootName = "") where T : new(),通过传入的实体集合对象和Xml根名称,可以转换成相应的XDocument,代码如下:
三、总结
以上的代码很少,主要通过重构来使代码简化。当然,将实体集合和实体转换为相应的string、XDocument、XElement、XDocument是非常简单的。单元测试的代码就不贴了,占地方。下篇随笔主要是如何将本文中转换的Xml进行匹配,本文所有的代码如下: