Reputation: 1
I'm building and XML file representing and Entity. After many hours this seems to be working, but is there a better way ?
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();
}
Upvotes: 0
Views: 217
Reputation: 32268
Yes, you can use the XmlSerializer, e.g.
XmlSerializer xs = new XmlSerializer(typeof(YourObjectType));
MemoryStream ms = new MemoryStream();
xs.Serialize(ms, yourActualObject);
string sampleXml = Encoding.UTF8.GetString(ms.ToArray());
Whether you're serializing your entity or a view of your entity, it works the same way. Just ensure whatever object you are serializing is serializable.
Upvotes: 2