我正在构建和表示实体的XML文件。经过几个小时,这似乎有效,但还有更好的方法吗?
var entityContents = (from p in context.people select p).ToListAsEnumerable();
var XmlString = CollectMemebersNameValue("people" , entityContents);
public static string CollectMemebersNameValue( string entityName, IEnumerable entityQuery)
{
var xmlText = new StringBuilder();
xmlText.AppendLine("<" + entityName + ">");
foreach (var item in entityQuery)
{
xmlText.AppendLine("<Row>");
foreach (var prop in item.GetType().GetProperties())
{
if ( ! prop.PropertyType.Name.Contains("ICollection"))
{
var nname = prop.Name;
var nvalue = prop.GetValue(item, null);
xmlText.AppendLine("<" + nname + ">" + nvalue + "</" + nname + ">");
}
}
}
xmlText.AppendLine("</" + entityName + ">");
return xmlText.ToString();
}
答案 0 :(得分:2)
是的,您可以使用XmlSerializer,例如
XmlSerializer xs = new XmlSerializer(typeof(YourObjectType));
MemoryStream ms = new MemoryStream();
xs.Serialize(ms, yourActualObject);
string sampleXml = Encoding.UTF8.GetString(ms.ToArray());
无论您是序列化您的实体还是实体视图,它的工作方式都是一样的。只需确保您序列化的任何对象 可序列化。