承接上篇「XML Attribute 匹配」,本文專注於將實體物件或集合序列化為各種 XML 表示形式 (string、XElement、XDocument、XmlDocument),採用重構簡化程式碼,不處理屬性別名,純示範核心轉換邏輯。
靜態類別提供 7 個公開方法,涵蓋單一實體與集合的各種輸出需求:
public static string ToXml<T>(IList<T> entities, string rootName = "") where T : new()
{
if (entities == null || entities.Count == 0) return string.Empty;
var sb = new StringBuilder();
sb.AppendLine(XmlResource.XmlHeader); //
XElement element = ToXElement(entities, rootName);
sb.Append(element.ToString());
return sb.ToString();
}
輸出範例:
<?xml version="1.0" encoding="utf-8"?>
<MapperInfoSet>
<MapperInfo>
<Name>MapperInfoIndex0</Name>
<CreatedTime>2012-02-19T08:54:44.9411601+08:00</CreatedTime>
...
</MapperInfo>
</MapperInfoSet>
public static string ToXml<T>(T entity) where T : new()
{
if (entity == null) return string.Empty;
return ToXElement(entity).ToString();
}
public static XElement ToXElement<T>(IList<T> entities, string rootName = "") where T : new()
{
if (entities == null || entities.Count == 0) return null;
if (string.IsNullOrWhiteSpace(rootName)) rootName = typeof(T).Name + XmlResource.XmlRootNameSuffix; // 預設 "MapperInfoSet"
XElement root = new XElement(rootName);
foreach (T entity in entities) root.Add(ToXElement(entity));
return root;
}
public static XmlDocument ToXmlDocument<T>(IList<T> entities, string rootName = "") where T : new()
{
if (entities == null || entities.Count == 0) return null;
XmlDocument doc = new XmlDocument();
doc.LoadXml(ToXml(entities, rootName));
return doc;
}
public static XElement ToXElement<T>(T entity) where T : new()
{
if (entity == null) return null;
XElement element = new XElement(typeof(T).Name);
foreach (PropertyInfo prop in typeof(T).GetProperties())
{
object val = prop.GetValue(entity, null);
element.Add(new XElement(prop.Name, val));
}
return element;
}
public static XDocument ToXDocument<T>(IList<T> entities, string rootName = "") where T : new()
{
if (entities == null || entities.Count == 0) return null;
return XDocument.Parse(ToXml(entities, rootName));
}
public static XElement ToXElement(Type type)
{
if (type == null) return null;
XElement element = new XElement(type.Name);
foreach (PropertyInfo prop in type.GetProperties())
element.Add(new XElement(prop.Name, null));
return element;
}
類別名+Set。轉換邏輯極簡單,關鍵在於善用 XElement 建構樹狀結構,再轉為所需輸出格式。下篇將示範如何解析本文產出的 XML 結構。
作者:JasenKin | 出處:https://www.cnblogs.com/jasenkin/