如何将列表转换为XML字符串和XML以列出它会产生错误 [英] How to convert list to XML string and XML to list it gives an error

查看:79
本文介绍了如何将列表转换为XML字符串和XML以列出它会产生错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class FeePlanGenerate
 {
     public List<FeePlan> FeePlanList { get; set; }
     public List<FeeComponent> FeeComponentList { get; set; }

     public string StudentName { get; set;}
     public string StudentAddress { get; set; }
     public string CurriculumName { get; set; }
     public string CourseName { get; set; }
     public string BCNumber { get; set; }
     public Nullable< DateTime> AddmissionDate { get; set; }
     public string AddmissionOfficer{ get; set; }
     public string Contant1 { get; set; }
     public string Contant2 { get; set; }
     public string AdmissionCode { get; set; }
     public Nullable< decimal> TotalInvoiceAmount { get; set; }
     public Nullable<decimal> TotalPayableFee { get; set; }
     public string ArrayOfFeePlanGenerate { get; set; }
 }





我的尝试:





What I have tried:

static string ConvertObjectToXMLString(object classObject)
        {
            string xmlString = null;
            XmlSerializer xmlSerializer = new XmlSerializer(classObject.GetType());
            using (MemoryStream memoryStream = new MemoryStream())
            {
                xmlSerializer.Serialize(memoryStream, classObject);
                memoryStream.Position = 0;
                xmlString = new StreamReader(memoryStream).ReadToEnd();
            }
            return xmlString;
        }
        public static FeePlanGenerate LoadFromXMLString(string xmlText)
        {
            XmlRootAttribute xRoot = new XmlRootAttribute();
            xRoot.ElementName = "user";
            // xRoot.Namespace = "http://www.cpandl.com";
            xRoot.IsNullable = true;
            var stringReader = new System.IO.StringReader(xmlText);
            var serializer = new XmlSerializer(typeof(FeePlanGenerate),xRoot);
            return serializer.Deserialize(stringReader) as FeePlanGenerate;
        }

推荐答案

上面提供的代码缺少几个类,所以我无法完全检查错误的位置是或正在遇到什么类型的错误。但是,我使用了自己的转换器代码,所有转换都没有错误。



这是我使用的:

The above code supplied is missing a couple of classes so I can't fully check where the error may be or what type of error that you are encountering. However, I used my own converter code and everything converted without an error.

Here is what I used:
public static class XmlConverter
{
    public static string FromClass<T>(T data)
    {
        string response = string.Empty;

        var ms = new MemoryStream();
        try
        {
            ms = FromClassToStream(data);

            if (ms != null)
            {
                ms.Position = 0;
                using (var sr = new StreamReader(ms))
                    response = sr.ReadToEnd();
            }

        }
        finally
        {
            // don't want memory leaks...
            ms.Flush();
            ms.Dispose();
            ms = null;
        }

        return response;
    }

    public static MemoryStream FromClassToStream<T>(T data, XmlSerializerNamespaces ns = null)
    {
        var stream = default(MemoryStream);

        if (data != null)
        {
            var settings = new XmlWriterSettings()
            {
                Encoding = Encoding.UTF8,
                Indent = true,
                ConformanceLevel = ConformanceLevel.Auto,
                CheckCharacters = true,
                OmitXmlDeclaration = false
            };

            try
            {
                XmlSerializer serializer = XmlSerializerFactoryNoThrow.Create(typeof(T));

                stream = new MemoryStream();
                using (XmlWriter writer = XmlWriter.Create(stream, settings))
                {
                    serializer.Serialize(writer, data, ns);
                    writer.Flush();
                }
                stream.Position = 0;
            }
            catch (Exception)
            {
                stream = default(MemoryStream);
            }
        }
        return stream;
    }

    public static T ToClass<T>(string data)
    {
        var response = default(T);

        if (!string.IsNullOrEmpty(data))
        {
            var settings = new XmlReaderSettings()
            {
                IgnoreWhitespace = true,
                DtdProcessing = DtdProcessing.Ignore
            };

            XmlSerializer serializer = XmlSerializerFactoryNoThrow.Create(typeof(T));

            using (var sr = new StringReader(data))
            using (var reader = XmlReader.Create(sr, settings))
                response = (T)Convert.ChangeType(serializer.Deserialize(reader), typeof(T));
        }
        return response;
    }
}

// ref: http://stackoverflow.com/questions/1127431/xmlserializer-giving-filenotfoundexception-at-constructor/39642834#39642834
public static class XmlSerializerFactoryNoThrow
{
    public static Dictionary<Type, XmlSerializer> cache = new Dictionary<Type, XmlSerializer>();

    private static readonly object SyncRootCache = new object();

    public static XmlSerializer Create(Type type)
    {
        XmlSerializer serializer;

        lock (SyncRootCache)
            if (cache.TryGetValue(type, out serializer))
                return serializer;

        //multiple variable of type of one type is same instance
        lock (type)
        {
            //constructor XmlSerializer.FromTypes does not throw the first chance exception           
            serializer = XmlSerializer.FromTypes(new[] { type })[0];
        }

        lock (SyncRootCache) cache[type] = serializer;
        return serializer;
    }
}



以下是如何使用它:


And here is how to use it:

var data = new FeePlanGenerate();
var xmlString = XmlConverter.FromClass(data);



UPDATE 我刚刚重新阅读了你的问题标题,并发现问题实际上与所提供的类中的List属性有关。



答案取决于XML的方式数据格式化。我的猜测是节点是一个在另一个之下,但是没有看到你要反序列化的原始XML很难说。



我最好的猜测是执行以下操作:


UPDATE I just re-read your question title and saw that the problem was in fact with the List properties in the class provided.

The answer is dependant on how the XML data is formatted. My guess is that the nodes are one beneath the other but without seeing the raw XML that you want to deserialize it is difficult to say.

My best guess would be to do the following:

public class FeePlanGenerate
{
    [XmlElement]
    public List<FeePlan> FeePlanList { get; set; }

    [XmlElement]
    public List<FeeComponent> FeeComponentList { get; set; }

    public string StudentName { get; set;}
    public string StudentAddress { get; set; }
    public string CurriculumName { get; set; }
    public string CourseName { get; set; }
    public string BCNumber { get; set; }
    public DateTime? AddmissionDate { get; set; }
    public string AddmissionOfficer{ get; set; }
    public string Contant1 { get; set; }
    public string Contant2 { get; set; }
    public string AdmissionCode { get; set; }
    public decimal? TotalInvoiceAmount { get; set; }
    public decimal? TotalPayableFee { get; set; }
    public string ArrayOfFeePlanGenerate { get; set; }
}


这篇关于如何将列表转换为XML字符串和XML以列出它会产生错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆