0

我正在构建和 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();
    }
4

1 回答 1

2

是的,您可以使用XmlSerializer,例如

XmlSerializer xs = new XmlSerializer(typeof(YourObjectType));
MemoryStream ms = new MemoryStream();
xs.Serialize(ms, yourActualObject);
string sampleXml = Encoding.UTF8.GetString(ms.ToArray());

无论您是序列化您的实体还是您的实体的视图,它的工作方式都是相同的。只要确保您要序列化的任何对象都是可序列化的

于 2013-05-03T15:35:59.260 回答