简体   繁体   中英

Entity to XML (EF5.0)

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();
    }

Yes, you can use the XmlSerializer , eg

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM